user3489476
user3489476

Reputation: 3

Define a property of a previously defined class

I have a class XYPerson with two properties: (NSString*) name and (NSNumber*) age I have an upper classe XYFamily with the following properties: XYPerson* Fahter, XYPerson* Mother...

Now I want to access to the age of the mother from a different object but I do not know how.

Any help is much appreciated.

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)
}

For a better understanding I posted two options of the code. By any reason option b) is not working and my question is what I am doing wrong. And is option a) correct?

Thanks again

Upvotes: 0

Views: 50

Answers (1)

Mundi
Mundi

Reputation: 80271

Make sure the properties of your persons which you want to excess from the family class are in the XYPerson.h file, so they are public.

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

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

Now it should work as expected (assuming float properties).

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

Upvotes: 1

Related Questions