请考虑构造数组并将其返回给父对象的问题。请查看下面的代码和评论。
我的问题是:为什么方法三有效,而方法一和二不用?
// ****************************
// Master.m
// ****************************
// Simply declare array and call accessor
NSMutableArray * allElementTypes;
allElementTypes = [ElementObject badElements];
// ****************************
// ElementObject.m
// ****************************
// Doesn't work (EXE_BAD_ACCESS)
+ (NSMutableArray*) badElements {
NSMutableArray * array = [[NSMutableArray alloc] initWithObjects:@"crab", @"poison", @"snake"];
return array;
}
// Doesn't work (EXE_BAD_ACCESS)
+ (NSMutableArray*) badElements {
return [NSMutableArray arrayWithObjects:@"crab", @"poison", @"snake"];
}
// WORKS
+ (NSMutableArray*) badElements {
NSMutableArray * array = [[NSMutableArray alloc] init];
[array addObject:@"crab"];
[array addObject:@"poison"];
[array addObject:@"snake"];
return array; // TODO: release this memory
}
答案 0 :(得分:11)
-arrayWithObjects:或-initWithObjects采用nil终止,可变长度的参数列表。
您写道:
[NSMutableArray arrayWithObjects:@"crab", @"poison", @"snake"];
你应该写的地方:
[NSMutableArray arrayWithObjects:@"crab", @"poison", @"snake", nil];