in the following piece of code I got from a book.
The NSString *pPath which is defined in the class as an instance variable.
@interface MainViewController : UIViewController {
NSString *pPath;
}
In the implementation after being set it is being retained. I assume that with the assignment the object is automatically retained (because it is an NSString) and there is no need to additionally retain it.
- (void) initPrefsFilePath {
NSString *documentsDirectory =
[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
pPath = [documen开发者_如何学GotsDirectory stringByAppendingPathComponent:
@"flippingprefs.plist"];
[pPath retain];
}
Yes, you need to retain your pPath variable if you obtain it this way. However it is not the end of the story - you also need to release its previous value otherwise it will just leak.
To make things easier you can use objective-c properties that allow you to automatically generate setter/getter methods with desired memory management behavior:
// header
@interface MainViewController : UIViewController {
NSString *pPath;
}
@property (nonatomic, retain) NSString* pPath;
// implementation
@synthesize pPath;
- (void) initPrefsFilePath {
NSString *documentsDirectory =
[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
self.pPath = [documentsDirectory stringByAppendingPathComponent:
@"flippingprefs.plist"];
}
Here in self.pPath=...
line automatically generated setter method will get called which:
- Will release previously set pPath value
- Will assign new value to pPath and retain it
You will also need to release your pPath variable in dealloc method:
-(void) dealloc{
[pPath release];
//or
self.pPath = nil;
[super dealloc];
}
精彩评论