简体   繁体   中英

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

Assume you parent class is, eg 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 ?

Thanks.

Yes you can, just use 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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