简体   繁体   English

访问无法修改的父类扩展中定义的Obj-C属性

[英]Accessing Obj-C property defined in parent class extension that you can't modify

Assume you parent class is, eg MyClass.m 假设您的父类是,例如MyClass.m

@interface MyClass()
  @property (nonatomic, readwrite, retain) NSString * str;
@end

And you inherit from this class and want to modify the value of str , is it possible without touching MyClass.m or MyClass.h ? 并且您从此类继承并且想要修改str的值,是否可以不触摸MyClass.mMyClass.h吗?

Thanks. 谢谢。

Yes you can, just use KVC: 是的,您可以,只需使用KVC:

 [anObject setValue:@"foo" forKey:@"str"];
 NSString* x =[anObject valueForKey:@"str"];

But don't do this . 但是不要这样 The property is hidden from the public interface in *.h because the developer of the parent class wanted to hide it. 该属性在*.h的公共接口中隐藏,因为父类的开发人员希望将其隐藏。

Eventually the developer of the parent class might just stop using the property. 最终,父类的开发人员可能只是停止使用该属性。 Then your code which uses this property will crash. 然后,使用此属性的代码将崩溃。

So, don't do this. 所以,不要这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM