对象 - 简单的方法来从NSObject的转换与性能的NSDictionary?(Obj-C eas

2019-06-23 22:47发布

我碰到的东西,我终于想通了,跑了,但是认为可能有一个更有效的方式来完成它。

我有一个对象,它有许多属性(标题,副标题,纬度,经度,信息等)的(一个NSObject其中通过的MKAnnotation协议)。 我需要能够到这个对象传递给另一个对象,这要提取使用objectForKey方法从它的信息,作为一个NSDictionary(因为这是它是从另一个视图控制器获得)。

我落得这样做是创建一个新的NSMutableDictionary和使用的setObject:forKey上每件的重要信息传递,然后我刚刚通过新创建的字典。

有没有更简单的方法来做到这一点?

下面是相关的代码:

// sender contains a custom map annotation that has extra properties...

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{    
    if ([[segue identifier] isEqualToString:@"showDetailFromMap"]) 
{
    DetailViewController *dest =[segue destinationViewController];

    //make a dictionary from annotaion to pass info
    NSMutableDictionary *myValues =[[NSMutableDictionary alloc] init];
    //fill with the relevant info
    [myValues setObject:[sender title] forKey:@"title"] ;
    [myValues setObject:[sender subtitle] forKey:@"subtitle"];
    [myValues setObject:[sender info] forKey:@"info"];
    [myValues setObject:[sender pic] forKey:@"pic"];
    [myValues setObject:[sender latitude] forKey:@"latitude"];
    [myValues setObject:[sender longitude] forKey:@"longitude"];
    //pass values
    dest.curLoc = myValues;
    }
}

在此先感谢您的集体智慧。


以下是我想出了,多亏了乡亲们,下面...

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{    
if ([[segue identifier] isEqualToString:@"showDetailFromMap"]) 
{
    DetailViewController *dest =[segue destinationViewController];
    NSArray *myKeys = [NSArray arrayWithObjects:
@"title",@"subtitle",@"info",@"pic",@"latitude",@"longitude", nil];

    //make a dictionary from annotaion to pass info
    NSDictionary *myValues =[sender dictionaryWithValuesForKeys:myKeys];

    //pass values
    dest.curLoc = myValues;
}

}

而一个更简单的修复,如下面看到的...

使用valueForKey而不是对象键来检索信息。


Answer 1:

如果属性都有相同的名称用于访问字典中的项,那么你可能刚使用KVC,不得不valueForKey:不是objectForKey

对于给定的这个词典范例

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

这个对象

@interface MyAnnotation : NSObject

@property (nonatomic, copy) NSString *title;

@end

如果我有字典的实例,或者它不会有问题MyAnnotation我可以打电话

[annotation valueForKey:@"title"];

显然,工程的其他方式,以及如

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


Answer 2:

当然可以! 使用objc运行时和KVC!

#import <objc/runtime.h>

@interface NSDictionary(dictionaryWithObject)

+(NSDictionary *) dictionaryWithPropertiesOfObject:(id) obj;

@end
@implementation NSDictionary(dictionaryWithObject)

+(NSDictionary *) dictionaryWithPropertiesOfObject:(id)obj
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];

    unsigned count;
    objc_property_t *properties = class_copyPropertyList([obj class], &count);

    for (int i = 0; i < count; i++) {
        NSString *key = [NSString stringWithUTF8String:property_getName(properties[i])];
        [dict setObject:[obj valueForKey:key] forKey:key];
    }

    free(properties);

    return [NSDictionary dictionaryWithDictionary:dict];
}

@end

你会使用这样的:

MyObj *obj = [MyObj new];    
NSDictionary *dict = [NSDictionary dictionaryWithPropertiesOfObject:obj];
NSLog(@"%@", dict);


Answer 3:

这是一个古老的职位和理查德·罗斯三世的回答是真正有用的,但在自定义对象的情况下(一个自定义的类还有一个自定义对象的话)。 然而,有时属性的其他对象等等,使得系列化有点复杂。

Details * details = [[Details alloc] init];
details.tomato = @"Tomato 1";
details.potato = @"Potato 1";
details.mangoCount = [NSNumber numberWithInt:12];

Person * person = [[Person alloc]init];
person.name = @"HS";
person.age = @"126 Years";
person.gender = @"?";
person.details = details;

对于这些类型的对象(多个自定义对象)转换成字典,我不得不修改理查德·罗斯III的回答:一点点。

+(NSDictionary *) dictionaryWithPropertiesOfObject:(id)obj
{
  NSMutableDictionary *dict = [NSMutableDictionary dictionary];

  unsigned count;
  objc_property_t *properties = class_copyPropertyList([obj class], &count);

  for (int i = 0; i < count; i++) {
      NSString *key = [NSString stringWithUTF8String:property_getName(properties[i])];
      Class classObject = NSClassFromString([key capitalizedString]);
      if (classObject) {
        id subObj = [self dictionaryWithPropertiesOfObject:[obj valueForKey:key]];
        [dict setObject:subObj forKey:key];
      }
      else
      {
        id value = [obj valueForKey:key];
        if(value) [dict setObject:value forKey:key];
      }
   }

   free(properties);

   return [NSDictionary dictionaryWithDictionary:dict];
}

我希望这会帮助别人。 全归功于理查德·罗斯III。



Answer 4:

为了完成理查德·罗斯的方法,这与一个自定义对象的NSArray的作品。

+(NSDictionary *) dictionaryWithPropertiesOfObject:(id)obj
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];

    unsigned count;
    objc_property_t *properties = class_copyPropertyList([obj class], &count);

    for (int i = 0; i < count; i++) {
        NSString *key = [NSString stringWithUTF8String:property_getName(properties[i])];
        Class classObject = NSClassFromString([key capitalizedString]);

        id object = [obj valueForKey:key];

        if (classObject) {
            id subObj = [self dictionaryWithPropertiesOfObject:object];
            [dict setObject:subObj forKey:key];
        }
        else if([object isKindOfClass:[NSArray class]])
        {
            NSMutableArray *subObj = [NSMutableArray array];
            for (id o in object) {
                [subObj addObject:[self dictionaryWithPropertiesOfObject:o] ];
            }
            [dict setObject:subObj forKey:key];
        }
        else
        {
            if(object) [dict setObject:object forKey:key];
        }
    }

    free(properties);
    return [NSDictionary dictionaryWithDictionary:dict];
}


Answer 5:

有这么多的解决方案,并没有什么工作对我来说,因为我有一个复杂的嵌套对象结构。 该解决方案采用由理查德和达米安的东西,但作为达明的解决方案是依赖于命名键作为类​​名即兴。

这里是头

@interface NSDictionary (PropertiesOfObject)
+(NSDictionary *) dictionaryWithPropertiesOfObject:(id)obj;
@end

这里是.m文件

@implementation NSDictionary (PropertiesOfObject)

static NSDateFormatter *reverseFormatter;

+ (NSDateFormatter *)getReverseDateFormatter {
if (!reverseFormatter) {
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
    reverseFormatter = [[NSDateFormatter alloc] init];
    [reverseFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
    [reverseFormatter setLocale:locale];
}
return reverseFormatter;
}

 + (NSDictionary *)dictionaryWithPropertiesOfObject:(id)obj {
NSMutableDictionary *dict = [NSMutableDictionary dictionary];

unsigned count;
objc_property_t *properties = class_copyPropertyList([obj class], &count);

for (int i = 0; i < count; i++) {
    NSString *key = [NSString stringWithUTF8String:property_getName(properties[i])];
    id object = [obj valueForKey:key];

    if (object) {
        if ([object isKindOfClass:[NSArray class]]) {
            NSMutableArray *subObj = [NSMutableArray array];
            for (id o in object) {
                [subObj addObject:[self dictionaryWithPropertiesOfObject:o]];
            }
            dict[key] = subObj;
        }
        else if ([object isKindOfClass:[NSString class]]) {
            dict[key] = object;
        } else if ([object isKindOfClass:[NSDate class]]) {
            dict[key] = [[NSDictionary getReverseDateFormatter] stringFromDate:(NSDate *) object];
        } else if ([object isKindOfClass:[NSNumber class]]) {
            dict[key] = object;
        } else if ([[object class] isSubclassOfClass:[NSObject class]]) {
            dict[key] = [self dictionaryWithPropertiesOfObject:object];
        }
    }

}
return dict;
}

@end


Answer 6:

您也可以使用NSObject+APObjectMapping类别,它可在GitHub上: https://github.com/aperechnev/APObjectMapping

这是一个退出容易。 刚刚描述类的映射规则:

#import <Foundation/Foundation.h>
#import "NSObject+APObjectMapping.h"

@interface MyCustomClass : NSObject
@property (nonatomic, strong) NSNumber * someNumber;
@property (nonatomic, strong) NSString * someString;
@end

@implementation MyCustomClass
+ (NSMutableDictionary *)objectMapping {
  NSMutableDictionary * mapping = [super objectMapping];
  if (mapping) {
    NSDictionary * objectMapping = @{ @"someNumber": @"some_number",
                                      @"someString": @"some_string" };
  }
  return mapping
}
@end

然后你可以在你的对象容易映射到词典:

MyCustomClass * myObj = [[MyCustomClass alloc] init];
myObj.someNumber = @1;
myObj.someString = @"some string";
NSDictionary * myDict = [myObj mapToDictionary];

您也可以从字典解析你的对象:

NSDictionary * myDict = @{ @"some_number": @123,
                           @"some_string": @"some string" };
MyCustomClass * myObj = [[MyCustomClass alloc] initWithDictionary:myDict];


文章来源: Obj-C easy method to convert from NSObject with properties to NSDictionary?