Greg
Greg

Reputation: 34798

how to prevent misuse of bool's in Core Data (i.e. forgetting to put "boolValue" to convert from NSNumber)

I still muck up with bool's in my core data config data. The NSManagedObject for say a core data "config" class one can quickly type in the following and you don't get an error:

  if (self.myCoreDataConfigObject.isOn) { ...

but it doesn't give the correct result as what is required is the conversion from NSNumber to a bool:

  if ([self.myCoreDataConfigObject.isOn boolValue]) { ...

Question - Any tips/tricks on how to avoid this? It would be great if XCode would show a warning in this case...

Upvotes: 0

Views: 105

Answers (3)

millimoose
millimoose

Reputation: 39960

One thing you could do is use the C99 bool type in if(). For instance, the following:

NSNumber *num = [NSNumber numberWithInt:0];

if (num == true) {
    NSLog(@"num is true");
}

makes XCode issue a warning. You'd have to adhere to a convention of always using "== true" in conditions though.

Upvotes: 0

chown
chown

Reputation: 52748

Under 'Targets' -> 'Build Settings' in the project settings there is a group of options for compiler warnings. I'm not 100% on this but turning on 'Pedantic Warnings' might do it, if not there are dozens of different settings for each different type of compiler. Try toggling some of them on and see if it generates a warning where you want one.

However, if (self.myCoreDataConfigObject.isOn) is a perfectly valid expression, so no errors (warnings maybe, but not errors) will ever get generated because using if(SOME_OBJECT) just checks if it is equivalent to nil or 0. (Unless, of course, you specify for the compiler to treat warnings as errors)

Upvotes: 0

Lily Ballard
Lily Ballard

Reputation: 185681

You could rename the field to something like isOnValue and then provide an accessor on your NSManagedObject subclass called isOn that runs the -boolValue conversion for you.

Don't forget, however, that "optional" values may be nil and you may care about this as something distinct than NO.

Upvotes: 1

Related Questions