09
retain/release
- (id)init
{
self = [super init];
if (self) {
NSLock *lock = [[NSLock alloc] init];
}
return self;
}
This is me, March 2011, the file Device_Controller.m. The method creates a lock, with which the program’s threads were supposed to keep one another away from a single device, puts it in the variable lock and ends. The variable exists until the closing brace. The object has a field of the same name, and I evidently meant to put the lock there, but the word NSLock at the start of the line created a new variable, which hid the field. The lock stayed in memory for ever, with nobody left who knew its address, and the field stayed empty. The program worked all the same, because a lock was later sent in from outside, and messages to an empty field are not considered an error in this language.
A few screens further down in the same file stands the method the system calls before destroying the object:
- (void)dealloc
{
[super dealloc];
}
By this point the object had managed to create four others, and this was the place to free them. Nothing is freed here.
The rules I was breaking took up one page in Apple’s documentation and were written in the language of property law. If you created an object with a method whose name begins with alloc, new or copy, you own it. If you need somebody else’s object for a long time, send it retain and you become a co-owner. When the object is no longer needed, every owner must send it release, once for each of his claims, and the object will vanish when the last one gives it up. Inside, the object has an ordinary counter, which retain increments and release decrements.
Free, one step away
The rest of the book is free
Leave your email and I will send a link to confirm it. Once you click it, every chapter opens here, on this device, for a year. When a new book comes out I will write to this address; reply “stop” to any email and I will not write again.
Have an INITE account? Sign in and the book opens without an email.
I do not charge for the book. If you would like to support it, you can donate from any chapter.
How your email is stored