Possible Duplicate:
Compare 2 string in objective-C
i try to compare equality between 2 NSString …
the 1st one is stored in the shared user defaults and the 2nd one is entered by the user thru a NSTextField …
is here is a little bit of my code (Xcode 4.5.2 Mac OS 10.7) …
1st the AppDelegate.h :
@interface AppDelegate : NSObject <NSApplicationDelegate>{
NSUserDefaults *administratifPref;
...
IBOutlet NSTextField *champProtection;
...
}
...
- (IBAction)poursuivre:(id) sender;
...
@end
and here the AppDelegate.m :
- (IBAction)poursuivre:(id)sender {
if([champProtection stringValue] == [champProtection stringValue]){
...
...
}
}
my question is : why the condition “if” is never verified ?!
i get no issues, no crash …
i did add 2 NSLog :
- (IBAction)poursuivre:(id)sender {
NSLog([champProtection stringValue]);
NSLog([administratifPref valueForKey:@"motdepasse"]);
if([champProtection stringValue] == [champProtection stringValue]){
...
...
}
}
and the returned values are the same 🙁
the only solution i found is doing :
- (IBAction)poursuivre:(id)sender {
BOOL result = [[champProtection stringValue] isEqualToString:[administratifPref valueForKey:@"motdepasse"]];
if(result == YES) {
...
...
}
}
so …
can anyone explain me the difference between these 2 ways of coding, that seem to be soooooo different ? (but that really seem the same for a newbee like me, who trust people who say that Cocoa is very simple ^^)
Objective-C is a strict superset of C. It adds objects by placing them behind opaque pointers — the asterisk in all Objective-C object declarations (typedefs aside) means that the actual thing you’re holding is a pointer to an object, i.e. its address in memory, rather than the object itself.
When you perform
==on two pointers you ask ‘do they both reference the same location in memory?’. If they do then both refer to the same object, so amongst other properties both pointers reference something of the same value.When you use
isEqual:(or one of its more specific siblings) you ask ‘regardless of their location, do these two objects have the same value?’, which is quite a different thing semantically.So the two things are quite different and in your case your description of the behaviour you want means you want to use the latter.