定义先前定义的 class 的 属性

Define a property of a previously defined class

我有一个 class XYPerson 有两个属性:(NSString*) name 和 (NSNumber*) age 我有一个 upper classe XYFamily 具有以下属性:XYPerson* Fahter, XYPerson* Mother...

现在我想从不同的对象访问母亲的年龄,但我不知道如何。

非常感谢任何帮助。

一)

#import „XYPerson.h“
#import „XYFamily.h“

NSMutableArray* community;          // array of family objects
XYFamily* family = [[XYFamily alloc] init]; // family element

for (int i=1;i < [community count]; i++)
{
  family = [community objectAtIndex:i];
  NSLog(@” %@ is %lu years old”, family.father.name, family.father.age)
}

b)

#import „XYPerson.h“
#import „XYFamily.h“

NSMutableArray* community;          // array of family objects
XYFamily* family = [[XYFamily alloc] init]; // family element
XYPerson* person = [[XYPerson alloc] init]; // person element

for (int i=1;i < [community count]; i++)
{
  family = [community objectAtIndex:i];
  person = family.father; 
  NSLog(@” %@ is %lu years old”, person.name, person.age)
}

为了更好地理解,我发布了代码的两个选项。无论出于何种原因,选项 b) 都不起作用,我的问题是我做错了什么。选项 a) 正确吗?

再次感谢

确保您想要从家庭 class 中超出的人的属性在 XYPerson.h 文件中,因此它们是 public。

// XYFamily.h
#import "XYPerson.h"

@interface XYFamily : NSObject 
@property (nonatomic, strong) XYPerson *father;
@property (nonatomic, strong) XYPerson *mother;
@end

现在它应该按预期工作(假设 float 属性)。

family.father.age = 50;
float aerageAge = (family.father.age + family.mother.age) / 2.0;