Re: resetting ivars safely
Re: resetting ivars safely
- Subject: Re: resetting ivars safely
- From: Daniel Child <email@hidden>
- Date: Thu, 13 Sep 2007 11:24:10 -0400
On Sep 13, 2007, at 5:13 AM, Uli Kusterer wrote:
On 12.09.2007, at 22:59, Daniel Child wrote:
+ (WordParser *) sharedWordParser
{
if (wordParser == nil) {
wordParser = [[WordParser alloc] init];
}
return wordParser;
}
I presume wordParser is some sort of global variable? I'd
recommend giving it a name like gWordParser (or sWordParser if it's
static, which will make it invisible to people outside your file).
Yes. OK, I'll do that.
- (id) init
{
if (self = [super init]) {
[self setSyllables: [[NSMutableArray alloc] init]];
[self setWordCandidates: [[NSMutableArray alloc] init]];
}
return self;
}
You're leaking here. Setters and getters (except those referring
to an "owner" or "delegate" (which usually is the owner)) generally
retain their objects themselves, so nobody is releasing these
arrays that you own because you allocate them using alloc/init.
I now understand my mistake. I thought the "alloc" above was balanced
by the release in the setter, but the setter also copies, so that's
not the case. Got it.
It seems to me there are two approaches.
A. Use a convenience constructor....
[NSMutableArray array] OR
[NSMutableArray arrayWithCapacity:]
But do I have to worry that it will get autoreleased prematurely?
B. Use alloc init autorelease [[NSMutableArray alloc] init]
autorelease].
Same question: could it get released too soon?
C. Use allloc + init and release elsewhere. But I'm not sure there is
an elsewhere that works. Is that correct?
// setter for wordCandidates ivar
- (void) setWordCandidates: (NSMutableArray *) wc
{
if (wc != wordCandidates) {
printf("wordCandidates retain count prior to release is %i.\n",
[wordCandidates retainCount]); // equal to 1
[wordCandidates release]; // EXC-BAD-ACCESS COMES HERE
wordCandidates = [wc mutableCopy];
}
}
If wordCandidates retain count prior to release is 1, that means
you're over-releasing somewhere. On the second call, due to your
leak, in the constructor, the retain count of the object should be
2: 1 for the alloc/init, 1 for the retain that setWordCandidates:
does.
Actually, I'm using release ... copy, but I guess it amounts to the
same thing.
Find the other places where you are releasing (or autoreleasing)
wordCandidates, and you should have your potential problem spots.
Post those, and we may be able to tell you which of them is wrong.
Will check. Thanks.
_______________________________________________
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