开发者

How to ensure no memory leak for Objective-C class that is called by many other class

I have the following controller class which will do different tasks based on combination of the flag and param property. The value of these two properties will be set by many other classes having a reference to this controller. The question is how does each of the calling class assign value and when should they release it so that there will be no memory leak ?

@interface 开发者_Python百科SampleController {
    NSMutableArray *param;  
    NSString *flag;
}
@property (nonatomic, retain) NSMutableArray *param;
@property (nonatomic, retain) NSString *flag;
@end


@implementation SampleController
@synthesize param;
@synthesize flag;

- (id)init
{
   param = [[NSMutableArray alloc] initWithCapacity:0];
   flag = @"nothing";
}
@end


Well it depends on how you call your controller :

  1. in an instance variable of an other object : you have to release it in this object's deallocate methode
  2. in a function : you should release it when you do not need it anymore (retained by another object for example or it finished the job in this function), if you want to return it, just sent the message "autorelease" to it and the NSAutoReleasePool will do the job for you.

To assign value, you can

  1. set the mutable array with the setParam:(*NSMutableArray)theArrayYouWantToReplaceYourArrayWith
  2. access it directly with [[yourSampleController param]addObject:(id)objectYouWantToAdd]...
  3. or more convenient : [yourSampleController.param addObject:(id)objectYouWantToAdd]

The addObject: message here is an example, you can see the methods for modifying an array (remove, sort,...) in the NSMutableArray class reference.

You will not be able to modify your string since it is a NSString and not a NSMutableString, but you can accessit by

  1. [yourSampleController getParam]
  2. [yourSampleController param]
  3. yourSampleController.param

If you want to avoid leaks in general, build your project with the Instrument tool in leak mode and look at the objects that are leaked if you found some that are declared in your functions. You can also check the Clang Static Analyzer (free static debugger) which is quite good if you have a lot of files.

I hope i helped you

Julien

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜