简体   繁体   中英

NSMutableArray having same reference

Facing an issue using NSMutableArray.Came across a requirement of adding empty mutableArrays into a NSMutableArray. When I removed the last array, all the arrays previously added also got removed from the Parent array. Code here,

NSMutableArray *collections = [[NSMutableArray alloc] init];

NSMutableArray *bookSet1 = [[NSMutableArray alloc] init];
[collections addObject:bookSet1];

NSMutableArray *bookSet2 = [[NSMutableArray alloc] init];
[collections addObject:bookSet2];

NSLog(@"bookSet1==bookSet2 %d", bookSet1==bookSet2);

[collections removeObject:bookSet2];

NSLog(@"Collections count==%d", [collections count]);

Result

ArrayTest[2356:c07] bookSet1==bookSet2 0 ArrayTest[2356:c07] Collections count==0

Checked whether they have same reference but the equals method returned false so they are definitely not pointing to the same memory location. Don't know why the behaviour is like this. Any possible solutions to overcome this.

Checked whether they have same reference but the equals method returned false

Nah. You were not checking the equality using isEqual . If you had used isEqual: , you would have gotten 1 (ie, YES ).

NSMutableArray (and all fundamental Cocoa collection classes) use isEqual: to determine if two objects are the same. This method can be overridden, and it's often used to make objects compare equal if their content is conceptually considered the same, not only if their memory address is identical (if the latter was true, we couldn't compare strings or any object like them safely, for example).

You can't really overcome that, since this is the expected and conceptually right behavior for removeObject: . If, for some reason, you can't go with it, you can always use the removeObjectIdenticalTo: method, which uses memory addresses for comparison ( documentation here ).

  1. removeObject: matches are determined on the basis of an object's response to the isEqual: message. I. e., objects are considered identical if their content are same.

  2. removeObjectIdenticalTo: matches are determined using object addresses. I. e., objects are considered identical if their object addresses are the same.

Try

[collections removeObjectIdenticalTo:bookSet2];

This will remove exact object which you want to remove ob the basis of address.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM