将消息发送到作为数组成员的对象

时间:2010-07-13 04:31:26

标签: objective-c

真的希望有人可以帮我理清为什么发送成为阵列成员的对象似乎是Obj-C中世界上最难的事情。

这是设置:我有一个汽车类。汽车有两个成员对象,发动机和轮胎(其中有四个)。然后我有一个NSArray(也是汽车的一员)初始化以保持轮胎对象。我这样做是因为我无法弄清楚如何编写或合成getter方法,只是像Tire *轮胎那样声明[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:]:索引(0)超出边界(0)'!!!

您知道,压力只是轮胎类的成员变量,并且已经合成了吸气剂方法。

然后我想在控制台上打印一些东西,比如“轮胎X的压力是X PSI”。

这让我疯了!这应该很简单! AHHHH。

提前致谢!

2 个答案:

答案 0 :(得分:1)

代码

        tire1 = [[tire alloc] init];

应该是

        tire1 = [[Tire alloc] init];

谁告诉你要将房产宣布为id?这是一个非常非常非常糟糕的做法,你现在应该停止它。现在。

如果你买了一本这样说的教科书,请把它烧成灰烬吧。

宣布你的财产

 @property (nonatomic, copy) Tire* tire; 

编译器警告你

        tire1 = [[tire alloc] init];

tire没有回复alloc

答案 1 :(得分:0)

哦,伙计。我觉得很傻。我根本没有初始化数组!我需要分配然后用initWithObjects初始化。哈哈。糟糕。