I have a BOOL property that I want to set in my class initializer.
@property (assign, nonatomic) BOOL isEditMode;
- (id)init
{
. . .
[self setValue:NO forKey:isEditMode];
return self;
}
The compiler gives me an "Incompatible integer to pointer conversion" warning. What am i doing wrong here?
The correct syntax to set a property is just
self.isEditMode = NO;
If you want to use -setValue:forKey:
you'd have to write it as
[self setValue:[NSNumber numberWithBOOL:NO] forKey:@"isEditMode"];
However, there's absolutely no reason to do this in your situation.
That said, since you're in an init
method, I would strongly recommend avoiding any property access whatsoever and instead using the ivar directly, as in
isEditMode = NO;
This avoids the possibility of an overridden setter being called (either in this class or a subclass) that makes the assumption that the object has already completed initialization. For this same reason you also want to avoid property access inside of -dealloc
.
The Key-Value Coding method setValue:forKey:
only accepts objects as arguments. To set a BOOL, you need to wrap the number in a value object with [NSNumber numberWithBool:NO]
. But there's little reason to do that. Key-Value Coding is a roundabout way to accomplish this. Either do self.isEditMode = NO
or just isEditMode = NO
. The latter is preferable in an init method (because setters can run arbitrary code that might not be desirable before an object is fully set up).
But to elaborate on the first point: The reason Key-Value Coding works this way is because the type system can't represent an argument that's sometimes an object and at other times a primitive value. So KVC always deals with objects and just autoboxes primitive values as necessary. Similarly, if you do [yourObject valueForKey:@"isEditMode"]
, you'll get back an NSNumber object wrapping the real value.
You can just assign the value directly:
isEditMode = NO;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With