iphone - 为什么静态 NSString 会泄漏?

标签 iphone objective-c ios memory-leaks

我有以下代码来检索我的 iOS 应用程序上的文件路径:

static const NSString * fullPathFromRelativePath(NSString *relPath)
{
    // do not convert a path starting with '/'
    if(([relPath length] > 0) && ([relPath characterAtIndex:0] == '/'))
        return relPath;

    NSMutableArray *imagePathComponents = [NSMutableArray arrayWithArray:[relPath pathComponents]];

    NSString *file = [imagePathComponents lastObject];    
    [imagePathComponents removeLastObject];

    NSString *imageDirectory = [NSString pathWithComponents:imagePathComponents];

    NSString *fullpath = [[NSBundle mainBundle] pathForResource:file
                                                         ofType:NULL
                                                    inDirectory:imageDirectory];
    if (!fullpath)
        fullpath = relPath;

    return fullpath;    
}

static const char * fullCPathFromRelativePath(const char *cPath)
{
    NSString *relPath = [NSString stringWithCString:cPath encoding:NSUTF8StringEncoding];
    const  NSString *path = fullPathFromRelativePath(relPath);
    const char *c_path = [path UTF8String];
    return c_path;
}

static const char * relativeCPathForFile(const char *fileName)
{        
    NSString *relPath = [NSString stringWithCString:fileName encoding:NSUTF8StringEncoding];        
    const NSString *path = fullPathFromRelativePath(relPath);
    const char *c_path = [[path stringByDeletingLastPathComponent] UTF8String];    
    return c_path;
}

我在调试控制台中收到了很多这样的消息:

objc[4501]: Object 0x6e17060 of class __NSCFString autoreleased with no pool in place - just leaking - break on objc_autoreleaseNoPool() to debug
objc[4501]: Object 0x6e12470 of class NSPathStore2 autoreleased with no pool in place - just leaking - break on objc_autoreleaseNoPool() to debug
objc[4501]: Object 0x6e12580 of class __NSCFData autoreleased with no pool in place - just leaking - break on objc_autoreleaseNoPool() to debug

代码有什么问题? (我什至将 iOS 5 与“自动”保留/释放等一起使用)

干杯。

最佳答案

当您在其堆栈中没有任何释放池的线程上自动释放对象时,会出现此消息。默认情况下,主线程上总是有一个自动释放池。它是在 UIApplicationMain() 函数中创建和管理的,该函数通常由应用的 main() 函数调用。但是,您创建的其他线程(使用 performSelectorInBackground:NSThread)没有适当的自动释放池,除非您专门将一个自动释放池放在那里,因此该后台线程上的任何自动释放对象没有池可以稍后释放它们,只会泄漏。

如果您要在后台线程中执行某些操作,您应该做的第一件事就是创建一个自动释放池。在 ARC 下,使用新的 @autoreleasepool 结构来做到这一点。

关于iphone - 为什么静态 NSString 会泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6475727/

相关文章:

iphone - 自定义 UITableViewCell 创建两次......让我发疯

javascript - while 循环内的 if 语句。它为什么要这样做?

iphone - 如何在 iOS 中动态声明的自定义 View 中添加 UITableView?

ios - didMoveToSuperview 没有被调用

ios - 带有注释图钉的 map ,例如 Foursquare、swift

iphone - 线程问题在 iOS 7 上表现不同

iphone - 如何在UIImageView中显示eps格式图片

ios - 如何使用 AutoLayout 和 IB 根据设备更改 UITextField 的高度

iphone - exteriorWhenContainedIn 未按预期工作

ios - 关闭 UIScrollView 中的键盘