我正在从json解析数据,并将它们动态添加到数组中。如果我添加它们的12个数据,那就ok了。但是当我要添加第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];
}
我想这是内存管理的一部分,但我找不到内容。
答案 0 :(得分:2)
您确定键@"data13"
有一个对象可能此键不存在并返回nil
。在这种情况下,您需要检查nil
并决定是否要添加它。如果您要添加它,只需添加[NSNull null]
,因为您必须使用继承NSObject
的对象。
编辑:请尝试在for循环中创建它并使用[NSString stringWithFormat.....]
答案 1 :(得分: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;
}
}
}];