0

好吧,我正在解析来自 json 的数据,并将它们动态添加到数组中。如果我添加其中的 12 个数据,就可以了。但是当我要添加第 13 个时,我得到了这个错误(不管第 13 个是什么):

EXC_BAD_ACCESS

这是我的代码:

HomeView.h

#import <UIKit/UIKit.h>

@interface HomeView : UIViewController{  
    NSMutableData *responseData;
}

@property (nonatomic, strong) NSMutableData *responseData;

@end

和我的实现文件:

@implementation HomeView
@synthesize responseData;

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"connectionDidFinishLoading");
NSLog(@"Succeeded! Received %d bytes of data",[self.responseData length]);

// convert to JSON
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];
    NSString *parsed_track=[res objectForKey:@"data1"];
    [tracks_condition addObject:parsed_track];
    parsed_track=[res objectForKey:@"data2"];
    [tracks_condition addObject:parsed_track];
    parsed_track=[res objectForKey:@"data3"];
    [tracks_condition addObject:parsed_track];
    parsed_track=[res objectForKey:@"data4"];
    [tracks_condition addObject:parsed_track];
    parsed_track=[res objectForKey:@"data5"];
    [tracks_condition addObject:parsed_track];
    parsed_track=[res objectForKey:@"data6"];
    [tracks_condition addObject:parsed_track];

   parsed_track=[res objectForKey:@"data7"];
    [tracks_condition addObject:parsed_track];
    parsed_track=[res objectForKey:@"data8"];
    [tracks_condition addObject:parsed_track];
    parsed_track=[res objectForKey:@"data9"];
    [tracks_condition addObject:parsed_track];
    parsed_track=[res objectForKey:@"data10"];
    [tracks_condition addObject:parsed_track];
    parsed_track=[res objectForKey:@"data11"];
    [tracks_condition addObject:parsed_track];
    parsed_track=[res objectForKey:@"data12"];
    [tracks_condition addObject:parsed_track];

  // parsed_track=[res objectForKey:@"data13"]; //HERE COMES THE ERROR
   // [tracks_condition addObject:parsed_track];

}

我想这是内存管理的问题,但我不知道是什么。

4

2 回答 2

2

你确定有一个对象 key@"data13"可能这个 key 不存在并返回nil。在这种情况下,您需要检查nil并决定是否要添加它。如果要添加它,只需添加它,[NSNull null]因为您必须使用继承的对象NSObject

编辑:请尝试在 for 循环中进行,并使用构造字符串[NSString stringWithFormat.....]

于 2012-08-26T11:41:02.580 回答
1

EXC_BAD_ACCESS 是因为您正在向nil数组中添加一个对象,或者在您将其添加到数组时该对象已经被释放。

另一方面,您可以使用 for 循环将对象添加到数组中,而不是使用多行代码:

for (NSUInteger idx = 1; idx <= [[res allKeys] count]; idx++) {

    if ([[[res allKeys] objectAtIndex:idx] rangeOfString:@"data"].location != NSNotFound)
        [tracks_condition addObject:[res objectForKey:[NSString stringWithFormat:@"data%d", idx]]];

}

甚至更好:

[self.questionInfo enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {

        if ([key rangeOfString:@"data"].location != NSNotFound && obj != nil) {

            [tracks_condition addObject:obj];

        }

        else {

            if ([tracks_condition count] >= 18) {
                *stop = YES;

            }                   
        }

}];
于 2012-08-26T12:17:17.757 回答