The rules are simple:
- Any object returned by
,alloc
,copy
, orcopyWithZone
has a retain count of 1.new
-
increases the receiving object's retain count.retain
-
decreases the receiving object's retain count.release
-
tells the current autorelease pool to send the receiving object theautorelease
message “later”.release
- Any factory method that doesn't have “new” or “copy” in the name (e.g.,
) returns an object that it has autoreleased on your behalf.stringWithString:
Or, digested a bit:
- Any method whose name contains
,copy
,alloc
, orretain
returns an object that you own.new
- Any method that doesn't, returns an object that you don't own.
- To own an object, retain it.
The incorrect implementation of
setName:
that you show is incorrect because it stores an autoreleased object in an instance variable, when you mean to own the object. You should retain it or, in this case, copy it. One way is to simply use
alloc
and
initWithString:
, as in the correct example you show; the other way would be
copy
.