Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way of setting a BOOL property

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?

like image 532
NSExplorer Avatar asked Dec 12 '11 23:12

NSExplorer


3 Answers

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.

like image 94
Lily Ballard Avatar answered Nov 18 '22 20:11

Lily Ballard


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.

like image 20
Chuck Avatar answered Nov 18 '22 20:11

Chuck


You can just assign the value directly:

isEditMode = NO;
like image 2
Matt Lacey Avatar answered Nov 18 '22 18:11

Matt Lacey