iphone - SBJSON 解析器内存泄漏

标签 iphone ios json parsing memory-leaks

我正在尝试使用 SBJSON 解析 JSON 提要,但每次我通过仪器运行它时,我都会在一行中遇到 100% 的内存泄漏。我肯定有不正确的地方,希望能有一些见识。

我有一个城镇的表格 View ,当您单击一个城镇时,该提要将运行并获取居住在该城镇的人员列表并在表格 View 中对其进行解析。但是,每次我将详细信息 View 弹出回城镇列表并进入新的详细信息 View 时,我都会遇到内存泄漏

 SBJsonParser *parser = [[[SBJsonParser alloc] init] autorelease];
            NSString *jsonString = [[NSString alloc] initWithData:[request responseData] encoding:NSUTF8StringEncoding];

        id response = [parser objectWithString:jsonString error:NULL]; //100.0% memory leak

        NSMutableDictionary *peopleDictionary = (NSMutableDictionary *)response;

        NSMutableArray *buildingArray = [[NSMutableArray alloc] init];

        if (peopleDictionary != nil) {
            for (NSDictionary *dict in peopleDictionary) {  
                Person *incoming = [[Person alloc] init];
                incoming.firstName = [dict objectForKey:@"firstName"];
                incoming.lastName = [dict objectForKey:@"lastName"];
                incoming.address = [dict objectForKey:@"address"];
                [buildingFeedArray addObject:incoming];
                [incoming release];
            }
        }
        [jsonString release];
        self.peopleArray = buildingFeedArray;
        [self.tableView reloadData];
        [buildingFeedArray release];

最佳答案

您创建了一个名为 buildingArray 的 NSArray,但随后将对象添加到 buildingFeedArray,并释放了 buildingFeedArray

您需要更改第 5 行:

NSMutableArray *buildingArray = [[NSMutableArray alloc] init];

收件人:

NSMutableArray *buildingFeedArray = [[NSMutableArray alloc] init];


你应该尽快释放对象,所以在你发布的代码中你没有在解析后使用 jsonString ,所以你应该直接释放它。


您还可以通过替换来简化代码:

SBJsonParser *parser = [[[SBJsonParser alloc] init] autorelease];
NSString *jsonString = [[NSString alloc] initWithData:[request responseData] encoding:NSUTF8StringEncoding];
id response = [parser objectWithString:jsonString error:NULL]; //100.0% memory leak
NSMutableDictionary *peopleDictionary = (NSMutableDictionary *)response;

与:

NSString *jsonString = [[NSString alloc] initWithData:[request responseData] encoding:NSUTF8StringEncoding];
NSDictionary *peopleDictionary = (NSDictionary *)[jsonString JSONValue];

JSONValue 是 SBJSON 框架添加到 NSString 的便捷方法,

而且您还没有在代码中修改 peopleDictionary,因此它不需要是可变的。
此外,无论您是否使用便捷方法,SBJSON 框架都不会返回可变对象,因此如果您尝试使用可变类的方法,编译器不会警告您,但应用程序会在您到达时崩溃它。

关于iphone - SBJSON 解析器内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6929855/

相关文章:

iphone - iOS iPhone 5 选择正确的 Storyboard

iphone - 有没有办法跟踪 App Store 访问者?

ios - 由于尝试写入我认为是可变字典的内容,当我重新进入 TableViewController 时崩溃

xcode - 无法使用 XCode 4 启动 .xcodeproj

javascript - Node : cannot parse a JSON via API

json - TensorFlow 将计算图导出为 XML、JSON 等

iphone - 模态 UIImagePickerController 被解除时的 UIView 通知?

iphone - sneakyness 的 cocos2d d-pad 有 UIKit 版本吗?

iphone - 如果我从项目构建阶段的编译源中删除所有文件,会发生什么情况?

json - 在 postman 中发布 objectId