开发者

should variable be retained or not? iphone-sdk

开发者 https://www.devze.com 2022-12-23 05:11 出处:网络
in the following piece of code I got from a book. The NSString *pPath which is defined in the class as an instance variable.

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:

  1. Will release previously set pPath value
  2. 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];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号