سؤال

My class has a BOOL property that needs to be set by another class, so I am trying to use a pointer. I'm declaring a property for it like this:

@interface SomeClass : SuperClass
{
    BOOL *_shared;
}
@property(nonatomic) BOOL *shared;

Is this the correct way to do this? Then I'd simply set and access the value like this:

*self.shared = YES;

Or is the proper way to set it as a retainable property?

هل كانت مفيدة؟

المحلول

No, you do not want to send a pointer to an instance variable so that some other class can set the instance variable. Doing so is fragile and breaks encapsulation. It is an awful design pattern.

It is also completely unnecessary.

If Instance A can "send a pointer" to Instance B, then Instance A can easily send a reference to itself to Instance B. From there, Instance B can simply do [instanceA setShared:YES];.

@interface B:UIViewController
@property(strong) A *controllerA;
@end

@interface A:UIViewController
@property BOOL dogDoorEnabled;
@end

@implementation A
...
- (void) doSomething
{
     B *b = .... get an instance of B ...;
     [b setControllerA: self];
}
@end

@implementation B
...
- (void) doSomethingElse
{
    BOOL isCheeseOnFire = ... calculate whether the cheese is burning ...;
    [[self controllerA] setDogDoorEnabled: !isCheeseOnFire];
}
@end

(Watch out for a retain cycle -- if A somehow retains B, directly or indirectly, then the (strong) reference to A from B will create a retain cycle. Call [b setControllerA:nil] when you want to break that cycle.)

Now, if there is some reason why you still think you need to send a pointer to the internal state of A to B, please update your question.

نصائح أخرى

I would use

@interface SomeClass { }
@property(nonatomic) NSNumber *shared;
...
self.shared = [NSNumber numberWithBool:YES]; // in the other class
if ([self.shared boolValue]) {...} // in SomeClass where you want to find what is set

No. The proper way is declaring a BOOL and not a pointer to a BOOL. When you want to send the pointer to BOOL to the next viewController you can send the address of the variable with the operator &.

in your interface:

@interface SomeClass {
    BOOL _shared
}

@property (assign) BOOL _shared ;

in your implementation:

[nextViewController setPointerToBool: &_shared] ;

As others have said, you should just use a BOOL instead of a pointer to a BOOL. Make it an assign variable, and you can simply assign to it and read it directly. Also, In the modern compiler you don't need to declare instance variables, and it seems to be a good practice not to.

@interface SomeClass

@property (assign) BOOL shared;

@end

In your implementation:

self.shared = YES;

When it comes to your view controller, instead of passing a pointer to the BOOL, just pass a pointer to the instance of SomeClass, and set it like this:

someInstance.shared = YES;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top