iphone - 多次保存大型 nsstring 文件会使应用程序崩溃

标签 iphone ios memory-leaks nsstring

下面的代码崩溃了。基本上我正在访问一个保存为文件的非常大的字符串(xml - 包含图像数据)......修改它并以新名称保存它......在分析时我没有看到任何泄漏这段代码……但是在重复这个过程 20-25 次之后……该应用程序在 iphone 3gs 上崩溃,内存警告级别为三,并且它也杀死了整个正在运行的应用程序……我找不到这个应用程序泄漏的任何地方引起内存警告....任何建议

NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *documents = [paths objectAtIndex:0];
 NSString *filename = [NSString stringWithFormat:@"%@.yyy",fileToDuplicate];
 NSString *initPath = [documents stringByAppendingPathComponent:filename];
 NSString *final = [NSString stringWithFormat:@"%@.yyy",[[alertView textFieldAtIndex:0] text]];
 NSString *finalPath = [documents stringByAppendingPathComponent:final];
 NSString *newName=[[[alertView textFieldAtIndex:0] text] copy];
 NSError *error;
 NSString *xml = [[NSString alloc] initWithContentsOfFile:initPath encoding:NSASCIIStringEncoding error:&error] ;
 NSString *xml_1=[xml stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"<file_name><name>%@.yyy</name></file_name>",fileToDuplicate] withString:[NSString stringWithFormat:@"<file_name><name>%@.yyy</name></file_name>",newName]];
NSString *xml_2=[xml_1 stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"<property_name>%@</property_name>",fileToDuplicate] withString:[NSString stringWithFormat:@"<property_name>%@</property_name>",newName]];
[xml_2 writeToFile:finalPath atomically:YES encoding:NSASCIIStringEncoding error:&error];
 xml=nil;
 [xml release];
 xml_1=nil;
 xml_2=nil;
 [self.mTableView reloadData];
 fileToDuplicate=@"";
 [newName release];
 [pool drain];
 return ;

最佳答案

如果您没有看到泄漏的地方,那么切换到 ARC。就像中间的一天一样清晰:

分配 xml

将变量 xml 设置为 nil (LEAK!!!!!)

释放 xml 的内容(为 nil)<--- 这什么都不做

最后两个是反的。您需要在将其设置为 nil 之前释放它。如果您不理解这个概念,我建议您阅读更多有关指针的内容。释放消息作用于指针的内容,而不是指针本身。后者没有意义。

关于iphone - 多次保存大型 nsstring 文件会使应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11595203/

相关文章:

iphone - 如何调整 UITableViewCell 的大小以使其适合任何详细信息文本标签

iOS Earl Gray - 选择缺少的参数

iphone - 位置设置与功耗统计

objective-c - 如何从自定义类创建和取消唯一的 UILocalNotification?

iphone - 如何从 uitableview 中选择值并将其显示在上一页的按钮上

ios - 在 Parse 中将字符串附加到数组中

没有 UILabels 的 iOS 动态表格 View 单元格高度

c# - SCardEstablishContext 内存泄漏

c++ - 将原始指针的所有权转移到 unique_ptr

c - Valgrind 说 "definitely leak"但它是吗?