The correct way to set the 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 the warning "Incompatible integer for pointer conversion". What am I doing wrong here?

+8
ios objective-c
source share
4 answers

The encoding method for the key value setValue:forKey: accepts objects only as arguments. To set BOOL, you need to wrap the number in a value object using [NSNumber numberWithBool:NO] . But there is no reason for this. Key value coding is a roundabout way to achieve this. Either do self.isEditMode = NO , or just isEditMode = NO . The latter is preferable in the init method (since installers may run arbitrary code, which may be undesirable, before the object is fully configured).

But in order to clarify the first point: the reason Key-Value Coding works this way because the type system cannot represent an argument, which is sometimes an object, and in other cases, a primitive value. Thus, KVC always deals with objects, and if necessary, only with the primitive values โ€‹โ€‹of autoboxes. Similarly, if you execute [yourObject valueForKey:@"isEditMode"] , you will return an NSNumber object that wraps the real value.

+16
source share

The correct syntax for setting a property is simply

 self.isEditMode = NO; 

If you want to use -setValue:forKey: you need to write it as

 [self setValue:[NSNumber numberWithBOOL:NO] forKey:@"isEditMode"]; 

However, in your situation there is no reason to do this.

However, since you are using the init method, I strongly recommend that you avoid any access to properties and use ivar directly instead, as in

 isEditMode = NO; 

This avoids calling the overridden setter (either in this class or in a subclass), which makes the assumption that the object has already completed initialization. For the same reason, you also want to avoid accessing properties inside -dealloc .

+5
source share

You can simply assign a value directly:

 isEditMode = NO; 
+2
source share

I think you mean:

 self.isEditMode = NO; 

If your code really compiles (I'm pretty new to Objective-C, so I don't know) setValue probably takes a pointer to a string ( @"isEditMode" , for example), rather than some other type ( isEditMode , for example).

+2
source share

All Articles