I encounter an error when I run this program from Chapter 8 of Cocoa Programming for Mac OSX by Aaron Hillegass.
The program binds a tableview to an array controller. In the setEmployees method of the array controller,
-(void)setEmployees:(NSMutableArray *)a
{
if(a==employees)
return;
[a retain];//must add
[employees release]; //must add
employees=a;
}
In the book, the two retain and release statements were not included and my program crashes whenever I try to add a new employee. After googling I found these two must-add statements to prevent program crashing.
I do not understand the memory management here. I am assigning a to employees. Why must I retain a if I am not deallocating anything? Why can I release employees before using it in the last assignment statement?
This is the standard pattern for setters using Manual Reference Counting (MRC). Step by step, this is what it does:
Under Automatic Reference Counting (ARC) the accessor can be simplified to:
The retains / releases are done for you. You haven’t said what sort of crash you are getting, but it seems like you are using ARC sample code in an MRC project.