addObject in NSMutableArray is copied or retained?
ios, nsmutablearray, objective-c
Solution
Collections retain, not copy, objects that are added to them.
Problem
When you add object into collection, such as `NSMutableArray`, the object is copied, that is, value semantics, or is retained, that is, reference semantics? I am confused in the example: ``` NSMutableString *testStr = [@"test" mutableCopy]; NSMutableArray *arrayA = [[NSMutableArray alloc] init]; [arrayA addObject:testStr]; NSLog(@"%@", arrayA); // output: test testStr = [@"world" mutableCopy]; NSLog(@"%@", arrayA); // output: test // testStr is copied - value semantics NSMutableArray *testArr = [@[@1, @2] mutableCopy]; NSMutableArray *arrarB = [[NSMutableArray alloc] init]; [arrarB addObject:testArr]; NSLog(@"%@", arrarB); // output: [1, 2] [testArr addObject:@3]; NSLog(@"%@", arrarB); // output: [1, 2, 3] // testArr is retained - reference semantics ``` You can see: if the object is a `NSMutableString`, it looks like the object is copied - you change the object will not affect the object in the array. However, if the object is a `NSMutableArray`, when you change the object, the object in the array also be changed - like you retain the object or pass by reference. Am I missing something here? Thanks.