Re: [self init] vs. [super init] in initWithCoder
Re: [self init] vs. [super init] in initWithCoder
- Subject: Re: [self init] vs. [super init] in initWithCoder
- From: John McLaughlin <email@hidden>
- Date: Sat, 19 Aug 2006 09:41:35 -0700
Hi Glenn,
You bring up a good point -- In my case I use Accessorizer
extensively so I never, ever, set anything except through setters so
I wouldn't leak (although it is arguable less efficient since you
init an object that then immediately get's deallocated)
As a side note, if you don't use Accessorizer then run, not walk to
http://www.kevincallahan.org/software/accessorizer.html Your code
will thank you for it
-John
On Aug 18, 2006, at 1:09 PM, glenn andreas wrote:
On Aug 18, 2006, at 2:53 PM, John McLaughlin wrote:
Hi All,
The consensus seems to be to have a private init function
('setDefaults') and then all of your inits' can call that. Seems
a reasonable approach that is certainly maintanable but a large
part of me still wonders that unless you need to call the parents
initWithCoder or unless you are doing something in your init that
is painful (time or resource wise) the most elegant solution would
still be to call [self init] first -- It guarantees an object's
starting point is the same whether loaded from a coder or
instantiated brand new and it really (again, to me) has a certain
elegance to it.
In general, you should only call an initializer once on an object -
so calling [self init] and then [super initWithCoder:] could cause
problems.
Consider a simple example:
@interface Foo : NSObject<NSCoding> { NSMutableDictionary *dict; }
@end
@implementation Foo
- (id) init
{
self = [super init];
if (self) {
dict = [[NSMutableDictionary dictionary] retain];
}
return self;
}
- (id) initWithCoder: (NSCoder *)aDecoder
{
self = [super init];
if (self) {
dict = [[aDecoder decodeObject] retain];
}
return self;
}
@end
If you make a subclass of Foo and in your initWithCoder call [self
init], that would end up allocating dict (in -[Foo init]), and then
[super initWithCoder:] will decode another dictionary, leaking the
old one.
Glenn Andreas email@hidden
<http://www.gandreas.com/> wicked fun!
quadrium2 | build, mutate, evolve, animate | images, textures,
fractals, art
John McLaughlin
http://www.loghound.com
email@hidden
Attachment:
smime.p7s
Description: S/MIME cryptographic signature
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden