iosobjective-cobjective-c-runtime

Why should I not use object_setIvar to set properties


I have a dictionary containing data for user from a REST endpoint. Here is my user class

#import <Foundation/Foundation.h>

@interface User : NSObject

@property (strong, nonatomic) NSString *uid;
@property (strong, nonatomic) NSString *email;
@property (strong, nonatomic) NSString *firstName;
@property (strong, nonatomic) NSString *lastName;
@property (assign, nonatomic) int status;

@end

I have a method to set all properties

/*
 * set properties
 */
- (void)setPropertiesWithDictionary:(NSDictionary *)dictionary{
    for(NSString *key in dictionary){

        object_setIvar(self,
                       class_getInstanceVariable([self class], [[@"_" stringByAppendingString:key] UTF8String]),
                       dictionary[key]);
    }
}

Instead of doing something like [user setUid:@dictionary[@"uid"]];

I want to call my method like this [user setPropertiesWithDictionary: dictionary];

Just wondering if implementing object_setIvar this way is fine. If not - Would be really great if you can explain why. Thanks in advance.


Solution

  • Do whatever you like, but why reinvent the wheel when key value coding (KVC) already exists? Just call this method:

    https://developer.apple.com/documentation/objectivec/nsobject/1417515-setvaluesforkeyswithdictionary?language=objc

    KVC does what you're trying to do, but it does it a lot better than you're likely to do it.

    https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/KeyValueCoding/index.html