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.
Gratis, solo falta un paso
El resto del libro es gratis
Deja tu correo y te mando un enlace para confirmarlo. Después del clic, todos los capítulos se abren aquí, en este dispositivo, durante un año. Cuando salga un libro nuevo, escribiré a esa dirección; responde “basta” a cualquier correo y no vuelvo a escribir.
¿Tienes cuenta INITE? Entra y el libro se abre sin correo.
No se cobra nada por el libro. Si quieres apoyarlo, puedes donar desde cualquier capítulo.
Cómo se guarda la dirección