Reputation: 65
Really hoping someone can help me sort out why sending objects that are members of an array seems to be the hardest thing in the world in Obj-C.
Here's the setup: I have a car class. Car has two member objects, engine and tire (of which there are four). Then I have an NSArray (also a member of car) initialized to hold the tire objects. I did this because I cannot figure out how to write or synthesize getter methods for just declaring like Tire *tires[4] (so I have to use NSArray and use objectAtIndex.
Here is the car class:
#import "Tire.h"
#import "Engine.h"
@interface Car : NSObject
{
Engine *engine;
Tire *tire1;
Tire *tire2;
Tire *tire3;
Tire *tire4;
NSArray *tirearray;
}
@property (nonatomic, copy) id engine;
@property (nonatomic, copy) id tire;
@property (nonatomic, copy) id tirearray;
@implementation Car
@synthesize engine;
@synthesize tire;
@synthesize tirearray;
- (void) print {
NSLog(@"%@", engine);
}
- (id) init {
if (self = [super init]) {
engine = [Engine new];
tire1 = [[tire alloc] init];
tire2 = [[tire alloc] init];
tire3 = [[tire alloc] init];
tire4 = [[tire alloc] init];
tirearray = [NSArray arrayWithObjects: tire1, tire2, tire3, tire4, nil];
}
return (self);
}
Then main:
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Car *car = [[Car alloc] init];
[[car.tirearray objectAtIndex:0] setPressure: 32];
[pool drain];
return 0;
}
What I'm trying to do is figure out how to send messages to the objects in the array! That's all I want to do. The above code builds, but returns uncaught exception 'NSRangeException', reason: '*** -[NSArray objectAtIndex:]: index (0) beyond bounds (0)' !!!
Just so you know, pressure is just a member variable of the tire class, and the getter methods have been synthesized.
Then I want to print something to the console like "The pressure of tire X is X PSI".
This is driving me nuts! This should be simple! AHHHH.
Thanks in advance!
Upvotes: 0
Views: 388
Reputation: 34185
The code
tire1 = [[tire alloc] init];
should be
tire1 = [[Tire alloc] init];
Who told you to declare a property as an id
? That's a very, very, very bad practice and you should stop it now. Right now.
If you bought a textbook which says so, please just burn it to ashes now.
By declaring your property
@property (nonatomic, copy) Tire* tire;
the compiler warn you at
tire1 = [[tire alloc] init];
saying that tire
doesn't respond to alloc
.
Upvotes: 1
Reputation: 65
Oh man. I feel so silly. I didn't initialize the array at all! I need to alloc then initialize with initWithObjects. Haha. Oops.
Upvotes: 0