views:

286

answers:

3

i'm an objective-c newcomer.

im trying to compare a core data entity attribute value and having trouble with the syntax. i just want to know the best way way to write the if statement to compare values.

in this example, the someAttribute attribute is a boolean, and its default is NO.

NSString *myValue = [NSString stringWithFormat:@"%@", myObject.someAttribute];
if ([myValue isEqualToString:@"1"]) {
 // do something 
} else {
 // do something else
}

is this the right way? i've tried other flavors, like below, but the results aren't accurate:

if (myObject.someAttribute == 1) {
if (myObject.someAttribute) {
+1  A: 

If your attribute is of BOOL type, this code will work fine

if(myObject.someAttribyte){
    //so smth if someAttribute is YES
}
Morion
+4  A: 

If you look in the generated header for this entity, there's a good chance that the actual type of the property is not BOOL, but NSNumber, which is how Cocoa boxes numeric types into objects. Assuming I'm right, you might try:

if ([myObject.someAttribute boolValue]) { ... }
Sixten Otto
yes, it is auto-generating as NSNumber
breaddev
and yes this works! thank you
breaddev
A: 

You can't convert a BOOL directly to a string.

Predicates are the preferred method of comparing CoreData values. It's more complicated to start but works better in the long run. See NSPredicate programming guide

TechZen
For fetching/sorting, sure. But for working with entities already loaded into memory?
Sixten Otto
exactly Sizten. at this point in my app, i've already been handed a custom object well after the fetch was done. i just dont know how to compare/convert NSNumber/Boolean values.
breaddev
my pasted code above (stringWithFormat) does the trick, but it doesnt seem right to me
breaddev
Predicates are very powerful and they're not just for fetching and sorting in databases. You can use them with any key-value coding compliant class. In this case, you would build a comparison predicate which would return a Boolean value. The advantage is that you don't have to fiddle with converting values back and forth between different types because the predicate will handle that for you. In general, their major advantages is that you can cram huge numbers of conditional branches into one line of code.
TechZen