Mailing Lists: Apple Mailing Lists
Image of Mac OS face in stamp
Re: NSArray retaining and releasing
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: NSArray retaining and releasing

NSArray *newArray = [NSArray arrayWithArray:oldArray];
[newArray retain];

Now I it is my responsobolity to send a release message to newArray. But am I responsible to send release messages to the contents of newArray?

No, the NSArray is responsible for its items.

How do I do a deep copy?

Would this work:

for(i=0;i<[oldArray count]; i++) {

  MyObj *temp = [[oldArray objectAtIndex:i] copy];
  [newArray addObject:temp];

It will work, but it will leak. Note that you have to send a release message to the temp object that you have created with "copy".

Is there an easier way to do deep copy of arrays?


NSArray *newArray = [[NSArray alloc] initWithArray:oldArray copyItems:YES];

But this requires MyObj to support the copy message. Do all objects in cocoa automatically support copy message (if they inherit from NSObject)?

NSObject does not implement it, subclasses have to. I think all Cocoa classes usually implement copy; at least the commonly used ones, especially of CoreFoundation.
Note that sometimes you have a mutable and an immutable version of a class (e.g. NSString vs. NSMutableString). The copy imlementation of immutable classes usually returns the same object - because it's immutable there is no need to have a "real" copy. But you don't have to worry about this.

iVolume - Loudness adjustment for iTunes.
LittleSecrets - The encrypted notepad.


Cocoa-dev mailing list (email@hidden)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)

Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden

 >NSArray retaining and releasing (From: Hrishikesh Muruk <email@hidden>)

Visit the Apple Store online or at retail locations.

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2011 Apple Inc. All rights reserved.