0

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

//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];
}
4

1 回答 1

3

如果这是在 MRC 下编译的(显然是这样),那么不会autorelease有内存泄漏。这是完全正确的。

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

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

- (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];
}
于 2013-11-14T13:14:27.410 回答