【问题标题】:Sending message to object that is member of array向作为数组成员的对象发送消息
【发布时间】: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


    【解决方案1】:

    代码

            tire1 = [[tire alloc] init];
    

    应该是

            tire1 = [[Tire alloc] init];
    

    谁让你将属性声明为id?这是一种非常、非常、非常糟糕的做法,你现在应该停止它。现在。

    如果你买了一本上面写着的教科书,现在就把它烧成灰烬吧。

    通过声明你的财产

     @property (nonatomic, copy) Tire* tire; 
    

    编译器会在

    处警告你
            tire1 = [[tire alloc] init];
    

    tire 没有回复alloc

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 1.不要写答案,修改问题。 2. 你现在得到的错误是什么,在哪里?
      • 谢谢。我刚开始使用 StackOverflow 并不太了解如何使用它。我会记住这一点的! “答案”不同于评论。明白了:P
      猜你喜欢
      • 2020-10-08
      • 1970-01-01
      • 1970-01-01
      • 2021-08-12
      • 2012-10-29
      • 1970-01-01
      • 2010-12-07
      • 2022-08-21
      • 2011-02-24
      相关资源
      最近更新 更多