我有这个功能,我不使用ARC:
-(NSString *)getDataFileDestinationPath
{
NSMutableString *destPath = [[NSMutableString alloc] init];
[destPath appendString:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]];
[destPath appendFormat:@"/%@.%@", dataFileName, dataFileExtension];
return destPath;
[destPath release];
}
因此,如果没有发布消息,我在泄漏分析中会有很大的内存泄漏。所以我添加了[destPath release];
消息但是当我尝试使用这个方法时 - 正如我在调试过程中看到的那样 - 这行代码根本没有被调用。因此,在返回消息后,控件转到下一个方法。我应该在哪里实现释放功能来释放内存?
答案 0 :(得分:3)
在这种情况下你需要使用自动释放。
-(NSString *)getDataFileDestinationPath
{
NSMutableString *destPath = [[NSMutableString alloc] init];
[destPath appendString:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]];
[destPath appendFormat:@"/%@.%@", dataFileName, dataFileExtension];
[destPath autorelease];
return destPath;
}
答案 1 :(得分:3)
这就是autorelease
的发明。
return [destPath autorelease];
或者最初不要对字符串对象进行alloc-init,只需创建一个最初自动释放的实例:
NSMutableString *destPath = [NSMutableString string];