views:

223

answers:

2

Example: I add some NSString objects to an NSMutableArray: @"Foo", @"Bar", @“FooBar". Now somewhere else I access that array again, and I want to delete @"Foo". So I create a new NSString @"Foo", and pass it to -removeObject:. The documentation does not state on what criteria -removeObject works. I think that it looks only for the memory adress, so in this case it would do nothing. Is that correct?

+3  A: 

according to the doc for removeObject: "matches are determined on the basis of an object’s response to the isEqual: message" and strings are compared with hashes ("If two objects are equal, they must have the same hash value") so, YES, that should be incorrect.

+1.You must have meant incorrect though -- see last sentence in question.
Oren Trutner
+1  A: 

Your example is an unfortunate one - if you use the string literal @"Foo" in two places in the code, the compiler will give them the same address (i.e. it uses the same static instance of the string). Example:

heimdall:Documents leeg$ cat foostrings.m

#import <Foundation/Foundation.h>

int main(int argc, char **argv)
{
    NSString *string1 = @"Foo";
    NSString *string2 = @"Foo";
    printf("string1: %p\nstring2: %p\n", string1, string2);
    return 0;
}

heimdall:Documents leeg$ ./foostrings

string1: 0x100001048

string2: 0x100001048

Graham Lee