Re: mutableCopy question
Re: mutableCopy question
- Subject: Re: mutableCopy question
- From: Clark Cox <email@hidden>
- Date: Fri, 11 Jun 2004 10:07:24 -0400
On Jun 11, 2004, at 09:28, Peter Schols wrote:
>
Hi,
>
>
I'd like to be able to duplicate my model objects (class Backup,
>
subclass of NSObject).
>
I've tried to implement this as follows (see below), but it
>
consistently crashes after duplication.
>
Any help would be appreciated.
>
>
Thanks in advance,
>
>
>
Peter
>
>
>
____________________________________________
>
>
In Backup.m:
>
>
- (id)mutableCopyWithZone:(NSZone *)zone
>
{
>
return(NSCopyObject(self, 0, zone));
>
}
>
>
>
In my controller class:
>
>
- (IBAction)duplicateBackup:(id)sender;
>
{
>
int i;
>
for (i = 0; i < [[backupsController selectedObjects] count]; i++) {
>
Backup *newBackup = [[[backupsController selectedObjects]
>
objectAtIndex:i]mutableCopy];
>
[newBackup setName:[[newBackup name]
>
stringByAppendingString:@" Copy"]];
>
[self insertObject:newBackup inBackupsAtIndex:[self
>
countOfBackups]];
>
[newBackup release];
>
}
>
}
I'm assuming that your setName: method will release the old name? If
this is the case, then you are over-releasing it. NSCopyObject will not
retain the instance variables of the object being copied, it will
simply copy the bytes. This means that after the copy, both the old
object's and the new object's instance variables point to the same
objects, but only one of them has retained them.
Make sure to retain (or better, copy) all of the object instance
variables in the newly made copy in your mutableCopyWithZone: method.
- (id)mutableCopyWithZone:(NSZone *)zone
{
Backup *newInstance = NSCopyObject(self, 0, zone);
newInstance->name = [newInstance->name copy];
newInstance->otherIVar = [newInstance->otherIVar copy];
return newInstance;
}
Or, as I often do (which may just be a hold over from my use of C++
copy constructors), provide an init method to do the copying, and have
mutableCopyWithZone:/copyWithZone: simply call through to it. e.g.:
-(id)initWithBackup:(Backup*)oldBackup
{
if(self = [super init])
{
[self setName: [oldBackup name]];
[self setSomeIVar: [oldBackup someIVar]];
//...
}
return self;
}
-(id)mutableCopyWithZone:(NSZone*)zone
{
return [[Backup allocWithZone: zone] initWithBackup: self];
}
For more information, see:
<
http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/
Tasks/ImplementCopy.html>
(That is all one URL, in case your mail client brok it into multiple
lines)
--
Clark S. Cox III
email@hidden
http://homepage.mac.com/clarkcox3/
http://www.livejournal.com/users/clarkcox3/
[demime 0.98b removed an attachment of type application/pkcs7-signature which had a name of smime.p7s]
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.