开发者

How does Object copying work in objective c

开发者 https://www.devze.com 2023-02-21 02:01 出处:网络
I\'m a bit confused on how copying objects works in Objective C. Here\'s what i know: When you copy an object, you get a distinct object in memory that contains all the same elements from the object t

I'm a bit confused on how copying objects works in Objective C. Here's what i know: When you copy an object, you get a distinct object in memory that contains all the same elements from the object that you have just copied and increments the retain count for each element. Also, copying each element in the array object from the original to a new location meant just copying the reference from one element of the array to another. So, the old and the new are pointing to the same element.

look at the below code: why is it that when you remove an object it only affects one object and when you change the element, it affects both the original and the copy object? Shoul开发者_StackOverflowdn't the remove affects both objects?

NSMutableArray *dataArray = [NSMutableArray arrayWithObjects:
                            [NSMutableString stringWithString:@"one"],
                            [NSMutableString stringWithString:@"two"],
                            [NSMutableString stringWithString:@"three"], nil];
NSMutableArray *dataArray2;
NSMutableString *mStr;

NSLog(@"1-dataArray: ");
for( NSString *elem in dataArray)
    NSLog(@"   %@", elem);

dataArray2 = [dataArray mutableCopy];
[dataArray2 removeObjectAtIndex:0];

NSLog(@"2-dataArray2: ");
for( NSString *elem in dataArray2)
    NSLog(@"   %@", elem);

mStr =[dataArray objectAtIndex:1];
[mStr appendString:@"ONE"];



NSLog(@"3-dataArray: ");
for( NSString *elem in dataArray)
    NSLog(@"   %@", elem);


NSLog(@"4-dataArray2: ");
for( NSString *elem in dataArray2)
    NSLog(@"   %@", elem);

[dataArray2 release];


mutableCopy performs a 'shallow copy' of the NSArray's contents. eg. it is copying the pointers (and presumably retaining them) from the origin array. It is not copying the data those pointers are pointing to.

If we were to do this explicitly it's essentially doing:

-(NSMutableArray*)mutableCopy
{
    NSMutableArray *newArray = [[NSMutableArray alloc] init];
    for (id elem in originalArray)
        [newArray addObject: elem];
    return newArray;
}

Though presumably it's doing it more efficiently by using its access to the internal data structures.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号