Can anyone tell me how I refer to these, is the first a system managed object and the second a user managed object, whats the terminology I should be using in objective-c / cocoa to refer to each of these?
01
+(Planet *) planet {
gPlanetCount++;
return [[[self alloc] init] autorelease];
}
int main(int argc, const char * argv[]) {
Planet *outerMost;
outerMost = [[Planet planet] retain]; // With
...
... some code
...
[outerMost release];
[pool drain];
return 0;
}
// OR
int main(in开发者_开发技巧t argc, const char * argv[]) {
Planet *outerMost;
outerMost = [Planet planet]; // Without
...
... some code
...
[pool drain];
return 0;
}
02
+(Planet *) newPlanet {
gPlanetCount++;
return [[self alloc] init];
}
int main(int argc, const char * argv[]) {
Planet *outerMost;
outerMost = [Planet newPlanet];
...
... some code
...
[outerMost release];
[pool drain];
return 0;
}
EDIT_001
So with the first example I would need to have something like this (text moved to 01 at the top)
EDIT_002
"Code cleaned up, revised final question below ..."
I am going to go with 01 (given that its the more usual way) can I ask again about the retain/release (i.e. if they are needed) this compiles and runs through the static analyser both with and without them?
gary
In your first example, the result of +planet
is autoreleased. Thus the caller must call -retain
on the result if it wants to maintain a reference to the result. +planet
is the more common pattern (although +[NSObject new]
exists, it's much more common in Cocoa-land to use and alloc/init
pair or a convenience constructor like your +planet
(which returns an autoreleased instance according to the Cocoa memory management rules).
In both examples, the result of +planet
/+newPlanet
is an instance of the Planet
class. There's no difference in terminology, but documentation of the (correct) first example might be explicit in stating the that the result is "autoreleased" even though the standard Cocoa memory management conventions would dictate that the result be autoreleased.
The actual object coming out of these methods is simply a Planet
object instance, as Barry Wark says in his answer. However, the first method (+planet
) would probably be referred to as a "convenience constructor".
EDIT_001
As I understand it, an autorelease
d object will stay around for the duration of the method/function it was created in. You only need to retain
the object if you want it to stay around longer than that.
精彩评论