简体   繁体   中英

objective-c: does addObjectsFromArray copy objects?

Having a hard time figuring this one out...

does addObjectsFromArray, a convenience method inside of NSArray copy everything, or does it keep the 'otherArray' parameter where it is in memory and do a LinkedList style point the tail to the 'otherArray' kind of move?

Im asking because I have pointers to important objects in some existing-array, but these pointers may point to a different object on an incoming-array.

I re-point my important-object-pointer to some object within the incoming-array, and then call addObjectsFromArray on the existing-array with the incoming-array.

My worry is that my re-pointed important-object-pointers will point to nothing if the incoming-array is actually copied, when ARC decides to nil out the incoming-array.

I think you're overthinking this. You won't have a pointer "into" an NSArray. You'll have a pointer to an object, and the NSArray will also have a pointer to that object. Reassigning your pointer will not change the pointer in the NSArray.

As for copying, NSArray does not copy objects. But as noted above, it does copy the pointer to the object, rather than holding a pointer-to-a-pointer or something weird like that. So in this code:

NSMutableString *a = [NSMutableString stringWithString:@"Cool"];
NSMutableString *b = a;
NSMutableArray *array = [NSMutableArray array];
[array addObject:a];
NSMutableString *c = [array objectAtIndex:0];
[b appendString:@" beans"];
a = nil;

At the end of running:

  • b and c will be hold same NSMutableString — "Cool beans" — and mutating either of them would show up in the other one

  • The array holds the same NSMutableString as b and c — "Cool beans" — and accessing the string there will also show mutations to the string

  • a will be nil. This didn't affect any of the other pointers to the string when we reset it, because they point to the string, not the variable.

When you addObjectsFromArray: , it is just as though you iterated over the array and added each individually. The other array could go away at that point and it wouldn't matter, because your NSArray now has pointers to all the objects.

I think that addObjectsFromArray works just like addObject : a pointer to the object is added to the array; the object itself is not modified except for its retain count, which is incremented.

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