无法在objective-c ios中释放变量[重复]

时间:2022-09-07 09:24:40

This question already has an answer here:

这个问题在这里已有答案:

I have this function, and I don't use ARC:

我有这个功能,我不使用ARC:

-(NSString *)getDataFileDestinationPath      
{
    NSMutableString *destPath = [[NSMutableString alloc] init];
    [destPath appendString:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]];
    [destPath appendFormat:@"/%@.%@", dataFileName, dataFileExtension];
    return destPath;
    [destPath release];
}

So without the release message I have a great memory leak in leaks analysis. So I added the [destPath release]; message but when I try to use this method - as I can see during the debug process - this line of the code wasn't called at all. So after return message the control goes to the next method. Where should I implement the release function to free the memory?

因此,如果没有发布消息,我在泄漏分析中会有很大的内存泄漏。所以我添加了[destPath release];但是当我尝试使用这种方法时 - 正如我在调试过程中看到的那样 - 这段代码根本没有被调用。因此,在返回消息后,控件转到下一个方法。我应该在哪里实现释放功能来释放内存?

2 个解决方案

#1


3  

This is what autorelease has been invented for.

这就是为自己发明的自动释放。

return [destPath autorelease];

Or initially don't alloc-init the string object, just create an originally autoreleased instance:

或者最初不要对字符串对象进行alloc-init,只需创建一个最初自动释放的实例:

NSMutableString *destPath = [NSMutableString string];

#2


3  

You need to use autorelease in this case.

在这种情况下,您需要使用自动释放。

    -(NSString *)getDataFileDestinationPath      
{
    NSMutableString *destPath = [[NSMutableString alloc] init];
    [destPath appendString:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]];
    [destPath appendFormat:@"/%@.%@", dataFileName, dataFileExtension];
    [destPath autorelease];
    return destPath;
}

#1


3  

This is what autorelease has been invented for.

这就是为自己发明的自动释放。

return [destPath autorelease];

Or initially don't alloc-init the string object, just create an originally autoreleased instance:

或者最初不要对字符串对象进行alloc-init,只需创建一个最初自动释放的实例:

NSMutableString *destPath = [NSMutableString string];

#2


3  

You need to use autorelease in this case.

在这种情况下,您需要使用自动释放。

    -(NSString *)getDataFileDestinationPath      
{
    NSMutableString *destPath = [[NSMutableString alloc] init];
    [destPath appendString:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]];
    [destPath appendFormat:@"/%@.%@", dataFileName, dataFileExtension];
    [destPath autorelease];
    return destPath;
}