我有一个父母。
标题文件(parent.h):
@interface Parent
@end
实现文件(parent.m):
@interface Parent {
// I defined a instance vaiable 'name'
NSString *name;
// another custom type instance variable
School *mySchool;
}
@end
@implementation Parent
...
@end
然后,我有一个继承 Parent
的Child
类。
标题(child.h):
@interface Child : Parent
-(void)doSomething;
@end
实现文件(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
如何访问来自子类功能在父类中定义的实例变量?
===========
我的意思是如何使用"名称"实例,不仅获得其值。例如:呼叫writetofile:atomeshy:编码:错误:在此处'name'此处
通过使用键值编码。
设置:
[self setValue:@"Hello" forKey:@"name"];
阅读:
NSString* name = [self valueForKey:@"name"];
[name writeToFile:@"Filename"
atomically:YES
encoding:NSUTF8StringEncoding
error:nil];
现在不推荐给代码中的用户ivars并在公共标头中声明ivars,但是如果您真的需要它,则可以使用此旧式代码:
//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