views:

120

answers:

1

Please consider a problem constructing an array and returning it to a parent object. Please have a look at my code and comments below.

My question is: Why does method THREE work while methods ONE and TWO do not?

// ****************************
// 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
}
+10  A: 

-arrayWithObjects: or -initWithObjects takes a nil terminated, variable length, list of arguments.

You wrote:

[NSMutableArray arrayWithObjects:@"crab", @"poison", @"snake"];

where you should have written:

[NSMutableArray arrayWithObjects:@"crab", @"poison", @"snake", nil];

Jim Correia
Ah nice! That was easy :).
Buffalo