Obj-C easy method to convert from NSObject with properties to NSDictionary?

后端 未结 6 938
感情败类
感情败类 2020-12-07 17:17

I ran across something that I eventually figured out, but think that there\'s probably a much more efficient way to accomplish it.

I had an object (an NSObject which

6条回答
  •  执念已碎
    2020-12-07 17:36

    If the properties had the same names as the keys used to access the dictionary then you could have just used KVC and had valueForKey: instead of objectForKey.

    For example given this dictionary

    NSDictionary *annotation = [[NSDictionary alloc] initWithObjectsAndKeys:
                                 @"A title", @"title", nil];
    

    and this Object

    @interface MyAnnotation : NSObject
    
    @property (nonatomic, copy) NSString *title;
    
    @end
    

    it wouldn't matter if I had an instance of the dictionary or MyAnnotation I could call

    [annotation valueForKey:@"title"];
    

    Obviously that works the other way as well e.g.

    [annotation setValue:@"A title" forKey:@"title"];
    

提交回复
热议问题