【发布时间】:2010-07-13 04:31:26
【问题描述】:
真的希望有人能帮我弄清楚为什么在 Obj-C 中发送作为数组成员的对象似乎是世界上最难的事情。
设置如下:我有一个汽车课。汽车有两个成员对象,发动机和轮胎(其中有四个)。然后我初始化了一个 NSArray(也是 car 的成员)来保存轮胎对象。我这样做是因为我不知道如何编写或合成 getter 方法来声明像 Tire *tires[4] (所以我必须使用 NSArray 并使用 objectAtIndex。
这是汽车类:
#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);
}
然后是主要的:
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;
}
我要做的是弄清楚如何向数组中的对象发送消息!这就是我想做的。上面的代码构建,但返回未捕获的异常 'NSRangeException',原因:'*** -[NSArray objectAtIndex:]: index (0) beyond bounds (0)' !!!
如你所知,压力只是轮胎类的一个成员变量,已经合成了getter方法。
然后我想在控制台打印一些东西,比如“轮胎 X 的压力是 X PSI”。
这快把我逼疯了!这应该很简单!啊啊啊。
提前致谢!
【问题讨论】:
标签: objective-c