Reputation: 42662
I have a parent class.
header file(Parent.h):
@interface Parent
@end
implementation file (Parent.m):
@interface Parent {
// I defined a instance vaiable 'name'
NSString *name;
// another custom type instance variable
School *mySchool;
}
@end
@implementation Parent
...
@end
Then, I have a Child
class which inherits Parent
.
header (Child.h):
@interface Child : Parent
-(void)doSomething;
@end
implementation file (Child.m):
@implementation Child
-(void)doSomething{
// Here, how can I access the instance variable 'name' defined in Parent class?
// I mean how to use the 'name' instance, not only get its value.
// for example: call writeToFile:atomically:encoding:error: on 'name' here
// tried to access mySchool defined in parent class
// Property 'mySchool' not found on object of type 'Parent'
School *school = [self valueForKey:@"mySchool"];
}
@end
How can I access instance variable defined in parent class from child class function?
==== Clarification ===
I mean how to use the 'name' instance, not only get its value. for example: call writeToFile:atomically:encoding:error: on 'name' here
Upvotes: 1
Views: 1406
Reputation: 4605
It's not recommended now to user ivars in code and declare ivars in public header, but if you really-really need that, then you can use this old-style code:
//Parent.h
@interface Parent: NSObject {
@protected
NSString *_name;
School *_mySchool;
}
@end
//Parent.m
@implementation Parent
...
@end
//Child.h
@interface Child : Parent
-(void)doSomething;
@end
//Child.m
@implementation Child
-(void)doSomething{
School *school = self->_mySchool;
NSString *name = self->_name;
}
@end
Upvotes: 0
Reputation: 21808
By using key-value coding.
Setting:
[self setValue:@"Hello" forKey:@"name"];
Reading:
NSString* name = [self valueForKey:@"name"];
[name writeToFile:@"Filename"
atomically:YES
encoding:NSUTF8StringEncoding
error:nil];
Upvotes: 1