Learing Cocoa Notes
I'm working through the tutorials on Cocoa at
MacResearch
- Cocoa is a framework built upon conventions. If you stick to the conventions, you will be fine; if you flout them, it will hurt.
- Typical init block:
-(id)initWithLeftValue:(double)lv andRightValue:(double)rv {
if ( self = [super init] ) {
leftValue = lv;
rightValue = rv;
}
return self;
}
- RULE: You should check the return value to see if it is nil after you call an initializer.
- RULE: Cocoa has the concept of a designated initializer, which is the initializer you should generally chain to from a subclass. There is no language support for the designated initializer; it is purely a convention, and, as such, typically involves no more than a statement to the effect in the comments or documentation.
- In Cocoa, when an object is ready to disappear, the method dealloc gets called.
- Typical pattern:
-(id)init... {
// Chain to designated initializer of superclass
if ( self = [super init] ) {
...
}
return self;
}
-(void)dealloc {
...
[super dealloc];
}
- Cocoa uses a system of memory management called reference counting
- Whenever an object is allocated, it automatically has a retain count of one. If you do nothing more with that object, it will remain in existence until the program exits. Other methods for creating objects, such as copy and new, also leave the object with a retain count of one.
- Often, some part of your program will want to make use of an object that it did not create itself. In such cases, you want to ensure that the object in question does not disappear when it is still needed. To achieve this, the object's retain method can be called, which increases the retain count by one.
- When an object is no longer needed, you call either the release method, or the autorelease method. Both methods decrease the retain count by one, but they differ in the timing of the change. release decreases the count immediatly.
- When you use autorelease, you are saying you are finished with the object, but maybe some other part of the program would like to make use of it for a bit longer. An example of this is when you need to return an object from a method, and you don't need the object anymore. If you call release, it will disappear before you can return it; if you call autorelease, you have time to return the object, and the calling code has a chance to retain it if it wants to keep it around.
- RULE: Whenever you call one of the retain count increasing methods, like alloc, retain, or copy, you should balance that with a call to a retain count decreasing method like release or autorelease.
0 comments:
Post a Comment