开发者

Am I giving Content or Memory address, Objective C

I have two different NSArray objects, lets say -

NSArray* a and NSArray* b

Array b is used to store textual content from csv file.

Now. if I do an operation like the following:

a = b;

Am I copying the content of b to a or am I making a point to b? In开发者_如何学Python the former case, changes made to array a won't be reflected in array b. On the other hand, in the latter case, they will be.

Thanks


Just a memory address (reference).

If you are coming from C development, you should know that the star * near the NSArray type means it is a pointer type. This is the same in Objective-C. (If you don't know C and this stuff about pointers, just forget it, as every object type in ObjC is a pointer, it is quite transparent to the final coder)

If you want to create an independant copy of b, so that modifying a does not modify b then, use the copy method. (If you do, don't forget to release it later, as any alloc/retain/copy have to be balanced by a release/autorelease call at the end)

Note anyway that an NSArray is immutable by construct, meaning that there is no method in the NSArray class to modify its content. So for your exact example, pointing to the same NSArray (without making a deep copy) is not really a problem as you can't modify an NSArray.

This is starting to become an issue only if you use a NSMutableArray, that do have methods to modify their contents. When working with mutable classes like NSMutableArray, you then should use mutableCopy to have a mutable copy (instead of copy which returns an immutable object)

Let me illustrate this in the following example:

NSMutableArray* a = [NSMutableArray arrayWithObjects:@"a",@"b",@"c"];
NSMutableArray* b = a; // points to the same object as a
NSArray* c = [[a copy] autorelease]; // immutable copy
NSMutableArray* d = [[a mutableCopy] autorelease]; // mutable copy, independant with a

// Now if you modify a...
[a addObject:@"d"];
// ...then b is also modified (it is the same object)
// but c and d aren't.
[d addObject:@"independant"];
// this does only modify d, but neither a, b or c.
// [c addObject:@"illegal"]; // <-- can't do this, addObject is a method of NSMutableArray, non-existing on NSArray.


Just the address.

If you want a copy you'd have to do something like:

a = [b copy];


Both a and b are 'pointers' to the memory address. When you assign a to the value of b, they are just now both pointing to the same memory address.

For more information on pointers:

http://www.cocoadev.com/index.pl?HowToUsePointers


Just memory address. There are explicit methods for you to create a copy of that array. However a simple assignment as above will not result in copying.

In C terms, both pointers are pointing to the same memory address.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜