NSString variable: should it be released?
When we create NSString object, do I need to release it?
When I run the static analyser for my application, i get the following
NSString *dataStr=[[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding]; Method returns an Objective-C objec开发者_StackOverflow社区t with a +1 retain count (owning reference)
The magic words are alloc
, copy
, and retain
: if any of them are used when the object is created or the property declared, you will need to release
it.
The reason the static analyser says that is because your method's name does not imply that the caller of the method has ownership of the object you're returning. There are a few solutions:
Modify your method's name so that it implies ownership of the returned object, i.e. these names imply ownership because they start with the word “new” or contain the word “copy”:
- (NSString *) newDataString
- (NSString *) copyDataString
If you use method names like the above, that means that the caller of the method is responsible for sending the object a
release
message when it is done with it.Modify your method so that it relinquishes ownership of the object before returning it using the
autorelease
method:- (NSString *) dataString { NSString *tmp = [[NSString alloc] initWithFormat:@"%f", 2.444]; return [tmp autorelease]; }
Remember, every
alloc
,copy
orretain
must be balanced with arelease
orautorelease
(but not both!).Read the Cocoa Memory Management Rules. These rules are not optional, you must follow them. The rules are also very simple. After a bit of practice they will become second nature.
Yes, you need to release it. Generally, any time you create an object pointer calling alloc
you will need to call release
.
Yes you need to release it. Every variable which having retain count must be release.
精彩评论