定义先前定义的类的属性

时间:2015-02-16 11:58:20

标签: objective-c class properties

我有一个XYPerson类,它有两个属性:(NSString *)name和(NSNumber *)age 我有一个上部classe XYFamily具有以下属性:XYPerson * Fahter,XYPerson *母亲......

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

非常感谢任何帮助。

A)

#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)是否正确?

再次感谢

1 个答案:

答案 0 :(得分:1)

确保您想要超出家庭成员的人的属性位于XYPerson.h文件中,因此它们是公开的。

// 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;