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
[yourObject isKindOfClass:[a class]] // Returns a Boolean value that indicates whether the receiver is an instance of // given class or an instance of any class that inherits from that class.
The goal of the @property directive is to configure how an object can be exposed. If you intend to use a variable inside the class and do not need to expose it to outside classes, then you do not need to define a property for it. Properties are basically the accessor methods. Its all about encapsulation.
It's Shorthand writing. In Objective-C, any character , numeric or boolean literal prefixed with the '@' character will evaluate to a pointer to an NSNumber object (In this case), initialized with that value. C's type suffixes may be used to control the size of numeric literals.
@objc means you want your Swift code (class, method, property, etc.) to be visible from Objective-C. dynamic means you want to use Objective-C dynamic dispatch.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With