Objective-c – setup the tires array below as an NSArray

cocoaobjective c

I have looked on the web but can't find anything that might help. My question is can I write the tires[x] array as an NSArray, if so what would be the syntax to both declare and allocate the tire Class instance objects?

@interface CarClass : NSObject {
    EngineClass *engine;
    TireClass *tires[4];        
}

.

@implementation CarClass
- (id) init {
    [super init];
    NSLog(@"_init: %@", NSStringFromClass([self class]));
    engine= [[EngineClass alloc] init];
    tires[0]= [[TireClass alloc] init];
    tires[1]= [[TireClass alloc] init];
    tires[2]= [[TireClass alloc] init];
    tires[3]= [[TireClass alloc] init];
    return self;
}

EDIT:

this is my dealloc method for the CarClass

- (void) dealloc {
    NSLog(@"_deal: %@", NSStringFromClass([self class]));
    [engine release];
    [tires release];
    [super dealloc];
}

Still a bit confused about the retain in the NSArray below, if I add an extra [tires retain] to the CarClass:init then the tires do not get released. However as the code is now the tires release with or without the end retain (i.e.)

tires = [[NSArray arrayWithObjects:
              [[[TireClass alloc] init] autorelease],
              [[[TireClass alloc] init] autorelease],
              [[[TireClass alloc] init] autorelease],
              [[[TireClass alloc] init] autorelease],
              nil] retain];

tires = [NSArray arrayWithObjects:
              [[[TireClass alloc] init] autorelease],
              [[[TireClass alloc] init] autorelease],
              [[[TireClass alloc] init] autorelease],
              [[[TireClass alloc] init] autorelease],
              nil];

FINAL EDIT: I also thought that without the autorelease on the individual tires that finally releasing the NSArray in the dealloc would release both the array and the objects it points to, this does not seem to be the case.

cheers -gary-

Best Answer

@interface CarClass : NSObject {
    EngineClass *engine;
    NSArray *tires;
}

.

@implementation CarClass
- (id) init {
    self = [super init];
    if (self == nil)
        return nil;
    NSLog(@"_init: %@", NSStringFromClass([self class]));
    engine= [[EngineClass alloc] init];
    tires = [[NSArray arrayWithObjects:
        [[[TireClass alloc] init] autorelease],
        [[[TireClass alloc] init] autorelease],
        [[[TireClass alloc] init] autorelease],
        [[[TireClass alloc] init] autorelease],
        nil] retain];
    return self;
}