views:

14

answers:

2

Hello, 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 division. 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.

+1  A: 

Try this instead if ([employee.department.division isEqualToString:@"Worldwide Seafood"])...

theMikeSwan
+1  A: 

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.

Barry Wark
Thanks! This worked, and the explanation is really helpful!
ed94133