Re: NSArray retaining and releasing
Re: NSArray retaining and releasing
- Subject: Re: NSArray retaining and releasing
- From: Manfred Schwind <email@hidden>
- Date: Sat, 3 May 2008 08:55:32 +0200
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?
Yes:
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.
Regards,
Mani
--
http://www.mani.de
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)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden