访问对象中对象的属性?

时间:2011-09-29 12:53:38

标签: objective-c

我有一个自定义的“大脑”类,它有一个自定义的“配方”对象作为其中一个属性。

配方类有四个“成分”对象作为属性。

如果我尝试做:

brain.myRecipe.ingredient1 = myIngredient;
self.displayLabel.text = brain.myRecipe.ingredient1.ingredientName;

标签是空白的(虽然我没有错误)

但如果我这样做

Ingredient * temp = myIngredient;
self.displayLabel.text = temp.ingredientName;

那个有效......你是不是可以用点运算符向下钻取这样的属性?

谢谢!

2 个答案:

答案 0 :(得分:1)

是的,您可以使用点运算符执行此操作。很可能其中一个属性是零。

答案 1 :(得分:1)

检查brain是否为零。

如果不是:

检查myrecipeingredient1属性?它们是否设置为retain
如果没有,请保留。

检查@synthesize两者。是不是有任何类型错误,所以他们的名字与属性和ivars的名称不匹配?
如果有错误(lokk吃上/下),请更正。

我还猜测Ingredient继承自NSObject(至少)并且在其init方法开始时有[super init]
如果没有,你是否继承NSObject,并先启动它。

如果没有任何作用......那么,只需添加更多代码。您希望我们如何用这么一小段代码来解决您的问题?

你应该有类似的东西:

Brain : NSObject {
   MyReceipe* receipe;
}

@property (nonatomic, retain) MyReceipe* receipe;



MyReceipe : NSObject {
   Ingredient* ingredient1;
}

@property (nonatomic, retain) Ingredient* ingredient1;



Ingredient : NSObject {
   NSString* ingredientName;
}

@property (nonatomic, retain) NSString* ingredientName;

在所有.m中,添加@synthsize the_property_name

之类的init方法
- (id) init {
   self = [super init];
   if (!self) return nil;

   self.the_ivar = nil; (or whatever you want)

   return self;
}
相关问题