开发者

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

开发者 https://www.devze.com 2023-04-08 22:30 出处:网络
I still muck up wi开发者_如何学Cth 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:

I still muck up wi开发者_如何学Cth 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...


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.


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)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消