How do I get the value from a class property in Objective-C?
I want to get variable value from an objective-c class, using reflection.
company.h looks like
@interface Company : NSObject {
}
@property (nonatomic, retain) NSString* phone;
- (NSString*) getPropertyValueByName: (NSString*) paramName;
company.m looks like
@implementation Company
@synthesize phone;
- (NSString*) getPropertyValueByName: (NSString*) paramName
{
id me = self;
value = [me objectForKey: paramName];
return value;
}
@end
I am using this like:
Company* comp =开发者_如何转开发 [Company new];
comp.phone = @"+30123456";
NSString* phone = comp.getPropertyValueByName(@"phone");
What I am getting is an exception:
-[Company objectForKey:]: unrecognized selector sent to instance
There is a much easier way to do it by using Key-Value-Coding.
There is already a way to get the value of a property by passing a string:
-(id)valueForKey:(NSString *)keyName;
You don't need to write your own methods for this.
That should be valueForKey instead of objectForKey. objectForKey is an NSDictionary instance method. Besides that there's a potentional mistake in your code. Your return type in the above method is string but you don't cast it to NSString before returning.Even if you're sure that it'll always return a string it's good practice to avoid any doubts. And when declaring an NSString property you should copy it rather than retaining it. And, what's the point in declaring a "me" variable if you can easily say:
[self valueForkey:paramName];
精彩评论