Re: NSDictionary allocation
Re: NSDictionary allocation
- Subject: Re: NSDictionary allocation
- From: Bill Bumgarner <email@hidden>
- Date: Mon, 14 May 2007 19:16:11 -0700
On May 14, 2007, at 4:44 PM, Boyd Collier wrote:
- (id)initWithSpagediData:(SpagediData*)spagediDataObj locus:
(int)locus;
@end
@implementation AlleleDictionary
- (id)initWithSpagediData:(SpagediData*)spagediDataObj locus:
(int)locus {
if ((self = [super init])) {
NSMutableDictionary *theAlleleDict = [[NSMutableDictionary alloc]
initWithCapacity:[spagediDataObj numberOfIndividuals] ];
// code that puts stuff into theAlleleDict (not shown)
self = [[NSDictionary alloc] initWithDictionary:
(NSMutableDictionary*)theAlleleDict copyItems:YES];
[theAlleleDict release];
}
return self;
}
@end
Then the code that calls the above looks like this:
AlleleDictionary *myDict = [[AlleleDictionary alloc]
initWithSpagediData:sharedData locus:0];
Although this seems to work, my gut feeling is that I'm possibly
creating a memory leak. Any comments/suggestions would be much
appreciated.
Why bother with a subclass and instance method at all?
You could add...
@interface NSDictionary
(DictionaryWithSpagediDataFactoryConvenienceMethodGoop)
+ (NSDictionary *) dictionaryWithSpagediData:
(SpagediData*)spagediDataObj locus: (int) locus
@end
... in a category on NSDictionary and then use it directly, retaining
the result if you need to keep it around.
@implementation NSDictionary
(DictionaryWithSpagediDataFactoryConvenienceMethodGoop)
+ (NSDictionary *) dictionaryWithSpagediData:
(SpagediData*)spagediDataObj locus: (int) locus
{
NSMutableDictionary *theAlleleDict = [[NSMutableDictionary alloc]
initWithCapacity:[spagediDataObj numberOfIndividuals] ];
// code that puts stuff into theAlleleDict (not shown)
return [theAlleleDict autorelease];
}
@end
As demonstrated, there isn't really much of a reason to create an
immutable copy of the mutable dictionary. As long as you have
compiler warnings enabled, anything trying to mutate the NSDictionary*
return value will produce a warning (your code compiles without
warnings, right? Right?!?!!).
b.bum
(all code in mail -- please forgive stupid errors).
_______________________________________________
Cocoa-dev mailing list (email@hidden)
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