Equality with CoreData string attribute not working
I can't see why this isn't working. I have two entities, let's call them Employees and Departments. And Departments has a String attribute called divisio开发者_开发知识库n. This works perfectly:
NSLog(@"Division: %@",employee.department.division);
The console shows, let's say, "Worldwide Seafood". But if I attempt a comparison with the exact same string, it fails:
if(employee.department.division == @"Worldwide Seafood") NSLog(@"Works in seafood!");
Nothing displays in the console, i.e. the comparison is not working as it should.
Make sense to anyone? Thanks.
Using ==
to compare NSObject
instances (in this case NSString
instances) is a pointer comparison since Objective-C instances cannot be created on the stack. Thus, your code asks whether the NSString
instance employee.department.division
is the same pointer (same memory location) as a static string. This is almost certainly not the case.
You should use
[employee.department.division isEqualToString:@"Worldwide Seafood"]
More generally, you should use -[NSObject isEqual:]
to compare object instances.
Try this instead if ([employee.department.division isEqualToString:@"Worldwide Seafood"])...
精彩评论