Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 227
Odys Avatar asked Jul 12 '11 10:07

Odys


People also ask

How do I find the class of an object in Objective-C?

[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.

What does @property do Objective-C?

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.

What does @() mean in Objective-C?

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.

What is @dynamic in Objective-C?

@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.


1 Answers

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.

like image 164
Abizern Avatar answered Oct 23 '22 21:10

Abizern