objective-c - 奇怪的 NSString 泄漏

标签 objective-c ios nsstring

这段代码给我带来了漏洞——100 次迭代超过 100 MB。如果我写 [imageName release] 它会崩溃并显示“消息已发送到已释放的实例”。我什至想不出问题的根源是什么。

NSString* imageName=[NSString stringWithUTF8String:(const char*)sqlite3_column_text(statement, 5)];
imageName =[imageName stringByReplacingOccurrencesOfString:@"-" withString:@"_"];
imageName =[imageName stringByReplacingOccurrencesOfString:@"." withString:@"-"];

[ret setQuestionImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:imageName ofType:@"jpg"]]]; 

最佳答案

问题是这些便捷方法创建的字符串和图像是自动释放的,而自动释放发生得不够早。但是,如果您明确释放它们,它们将在自动释放时被双重释放。尝试将所有迭代包装到一个自动释放池中:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *imageName=[NSString stringWithUTF8String:(const char *)sqlite3_column_text(statement, 5)];
imageName = [imageName stringByReplacingOccurrencesOfString:@"-" withString:@"_"];
imageName = [imageName stringByReplacingOccurrencesOfString:@"." withString:@"-"];

[ret setQuestionImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:imageName ofType:@"jpg"]]];
[pool release];

关于objective-c - 奇怪的 NSString 泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11719410/

相关文章:

iphone - 如何让 YouTube 视频在 UIWebView 中开始自动播放

ios - 如何在 iOS 中的图像上应用 CIPhotoEffectMono 滤镜?

ios - NSURLComponents elementsWithString - 规则

ios - 删除多余的空白

objective-c - 在 Objective-C block 中遇到 BOOL 返回类型问题

ios - objective-c : Get ISO Formated Date from String '2015-11-25T00:00:00.000Z'

ios - Xcode 中的 "Dead Store"警告

ios - 在长字符串中修改时间格式正则表达式的发生

objective-c - Cocoa 中的 OCR(从照片中读取文本)?

ios - 将 NSMutable 字典保存到文档时遇到问题。 UIImage 不会保存/显示