我注意到在目标 c 中对初始化的空 NSMutableArray 执行 for/in 操作没有按预期工作。
简化代码是:
+(void) convertArray: (NSMutableArray*)arrayIN {
NSMutableArray *arrayOUT = [NSMutableArray array];
NSLog(@"is nil %d - count %d", !arrayIN, [arrayIN count]);
for(NSObject *o in arrayIN)
[arrayOUT addObject:[o convertToAnotherClass]];
}
实际代码是:
+(BOOL) writeTasks: (NSArray*)tasksArray {
NSMutableArray *arr = [NSMutableArray array];
NSLog(@"is nil %d - count %d", !arr, [arr count]);
for(Task *t in tasksArray)
[arr addObject:[t getDictionary]];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
if (! jsonData) {
NSLog(@"Got an error: %@", error);
return NO;
} else {
//NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[jsonData writeToFile:path options:NSDataWritingAtomic error:nil];
return YES;
}
}
令人惊讶的是,执行[dummyClass convertArray:[NSMutableArray array]]
显示了这一点:
2012-06-25 13:51:34.236 Planorama[740:707] is nil 0 - count 0
2012-06-25 13:51:34.239 Planorama[740:707] -[__NSArrayM convertToAnotherClass]: unrecognized selector sent to instance 0xde9b580
(lldb)
为什么 ?arrayIN 为空,为什么convertToAnotherClass
还要调用?