DDukesterman
DDukesterman

Reputation: 1399

Inheritance from other class in Xcode

I am doing an example for Person and PersonChild classes. I was wondering why I can get this Int from the Person Class.

//Main

#import <Foundation/Foundation.h>
#import "Person.h"
#import "PersonChild.h"

int main(int argc, const char * argv[]){
    @autoreleasepool {
        PersonChild *Ben = [[PersonChild alloc]init];
        Ben.age = 25;  <-- Property 'age' not found on object of type 'PersonChild *'
        [Ben printThing];
    }
    return 0;
}

//Person class

#import "Person.h"

@implementation Person
@synthesize age, weight;

@end

//Person.h

#import <Foundation/Foundation.h>

@interface Person : NSObject{
    int age;
}
@property int age, weight;
@end

//PersonChild class

#import "PersonChild.h"

@implementation PersonChild

-(void) printThing{
   NSLog(@"%i", age);
}
@end

//PersonChild.h

#import <Foundation/Foundation.h>
#import "Person.h"

@class Person;
@interface PersonChild : NSObject

-(void) printThing;

@end

Upvotes: 0

Views: 2705

Answers (2)

Khaled Barazi
Khaled Barazi

Reputation: 8741

Unless you have listed your headers incorrectly, "age" is a property of person.h while "Ben" is an instance of personChild.h

The instance variable (iVar) used by any instance of a class must be declared in that class (or a superClass) as an instance variable.

I think you are confusing inheritance and importing. What you are doing above is importing Person.h into PersonChild.h and assuming that this will cause all of the "Person" class iVars to be available in "PersonChild" class.

One way to understand the difference is to change PersonChild.h to the following. Note how adding Person on the @interface line is the right way to say PersonChild class inherits from Person class. This should fix your bug.

#import <Foundation/Foundation.h>
#import Person.h    

@interface PersonChild : Person

-(void) printThing;
@end

Hope this helps

Upvotes: 0

Odrakir
Odrakir

Reputation: 4254

PersonChild is not inheriting from Person. The correct syntax for PersonChild.h is:

#import "Person.h"
@interface PersonChild : Person

Upvotes: 3

Related Questions