IOS @property,@synthesize内存泄漏

时间:2013-11-14 13:13:22

标签: ios memory-management memory-leaks

我正在开发一个IOS应用程序。我用XCode intruments进行了分析,如果我不写自动释放然后显示“潜在的内存泄漏”消息。这是下面的代码块中的错误。我不确定。

//TransferList.h
@property (nonatomic,retain) WebServiceAPI *webApi;


//TransferList.m
@implementation TransferList

@synthesize webApi;

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.webApi = [[[WebServiceAPI alloc] init] autorelease];
}

- (void)dealloc
{    

    [webApi release];
    [super dealloc];
}

1 个答案:

答案 0 :(得分:3)

如果这是在MRC下编译的(显然是),那么没有autorelease就会出现内存泄漏。这是绝对正确的。

alloc表示您想要对象的所有权 分配给retain的财产也声称拥有权(由财产) 在dealloc中,您正在释放该属性(该属性将不再拥有该对象)。

如果没有autoreleaseviewDidLoad将永远不会失去对象的所有权,并且您将有内存泄漏,因为该对象将永远不会被释放。

- (void)viewDidLoad {
    [super viewDidLoad];

    //create the object and get the ownership
    WebServiceAPI *api = [[WebServiceAPI alloc] init];

    //let our property also own this object
    self.webApi = api;

    // I don't want to own the object anymore in this method
    // (of course, using autorelease is simpler)
    [api release];
}

- (void)dealloc {    
    //our property doesn't want to own the object any more
    [webApi release];
    [super dealloc];
}
相关问题