Leem.fin Leem.fin - 5 months ago 21
iOS Question

Access parent class instance variable from child class function

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

Answer

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];
Comments