Noob question regarding program crash
Hello,
i m currently reading 'Cocoa Programming for MAC OS X' and have stumbled upon a problem that i cant find a solution to. In the 'RaiseMan' application in chapter 8 of the book, there is the following class:
@interface MyDocument : NSDocument
{
NSMutableArray *employees;
}
-(void)setEmployees:(NSMutableArray *)a;
@end
and at the implementation file:
@implementation MyDocument
...
-(void)setEmployees:(NSMutableArray *)a
{
if (a == employees) return;
[a retain]; // comment this a get a crash
[employees release];
employees = a;
}
@end
Now when i comment the line saying [a retain], i get a crash. Could someone enlighten me ? I use the garbage collector and usually i dont write code with release/retain. Is this bad ?
From what I know, you don't have to retain that variable. It gets released automatically, and since you've retained it, you have to release it. You've destroyed the employees object -- you have to re-alloc it too.
I may be wrong, of course. I've barely learnt the Objective-C language. But I'd recommend "Programming in Objective-C 2.0" (Stephen Kochan) which is how to learn the real language. If you have it, check out Chap. 17.
K's correct that this could be a retain issue.
However I'm more suspicious of a typo in the calling code. If a is a valid object pointer (or a == nil), then this should not crash. Did you download the code from Aaron Hillegass' web site, or type it in from the book?
The point of the code if ( a == employees ) return ; // do nothing if the caller is telling us something we know
[a retain]; // bump the reference code[employees release]; // release the old guys
employees = a ; // assign employees
This is very much 'boiler-plate' code in Obj/C and looks safe to me. However if you have something horrible in the calling code, we all bets are off.
@clanmills: This is The Book. You could take a look at RaiseMan to see what it is. (p. 127)
The code looks just like the book's, with one difference: the return statement is on the next line.