theDuncs
theDuncs

Reputation: 4843

CoreData convert NSNumbers to BOOL

I have an entity in my CoreData model which has a boolean field. This is stored on the CoreData Entity as an NSNumber. What I'd like is for the accessors to use BOOL and not NSNumber, so I can use

comment.isActive = YES;

instead of:

BOOL isCommentActive = [NSNumber numberWithBool:comment.isActive];

I was going to change the code in the auto-generated entity class file, but I was told not to do this since it overwrites each time I extract the model.

I have a category for the entity, and I tried coding an accessor which converts it to a BOOL of the same name, but this just resulted in me getting stuck into a loop.

Some people have mentioned method twizzling, but it sounds pretty hacky to me. Should i just create an accessor which returns a primitive of a different name?

Upvotes: 3

Views: 3848

Answers (2)

Satheesh
Satheesh

Reputation: 11276

I agree with Martin but you can try adding this function in your existing NSManagedObject subclass:

 -(void)setActiveRaw:(BOOL)active
 {
     [self setActive:[NSNumber numberWithBool:active]];
 }

And use it like this:

 [comment setActiveRaw:YES];

instead of

 comment.active = [NSNumber numberWithBool:comment.isActive];

And you can write a getter for this too:

 -(BOOL)getActiveRaw
 { 
    return [self.active boolValue]
 }

Upvotes: 0

Martin R
Martin R

Reputation: 540145

Just choose the option "Use scalar properties for primitive data types" when creating the managed object subclasses in Xcode. This will create the property

@interface MyEntity : NSManagedObject
@property (nonatomic) BOOL active;
@end

and all conversions are done automatically "under the hood". It is actually more efficient, because no NSNumber objects are created.

Unfortunately, the "Core Data Programming Guide" is outdated with respect to this, it still claims:

You can declare properties as scalar values, but for scalar values Core Data cannot dynamically generate accessor methods—you must provide your own implementations.

The only Apple "documentation" that I know of is the WWDC 2011 sessions videos, compare https://stackoverflow.com/a/14091193/1187415.

Upvotes: 12

Related Questions