真的希望有人能帮我理清为什么发送数组成员的对象似乎是Obj-C世界上最难的东西。发送消息给数组成员对象
这是设置:我有一个汽车类。汽车有两个成员对象,发动机和轮胎(其中有四个)。然后我有一个NSArray(也是汽车的一员)初始化以保持轮胎物体。我这样做是因为我无法弄清楚如何写或合成getter方法只是声明一样胎*轮胎[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)'!!!
大家知道,压力只是轮胎类的一个成员变量,并且吸气剂方法已经被合成。
然后我想打印一些东西给控制台,比如“轮胎压力X是X PSI”。
这让我疯狂!这应该很简单! AHHHH。
在此先感谢!
但我仍然得到一个错误。请帮忙!!! – 2010-07-13 04:46:28
1.不要写回答,修改问题。 2.你现在得到什么错误以及在哪里? – JeremyP 2010-07-13 07:46:28
谢谢。我刚开始使用StackOverflow,并没有完全知道如何使用它。我会牢记这一点! “答案”与评论不同。明白了:P – 2010-07-13 14:13:03