15

我遇到了一些我最终想通的东西,但认为可能有一种更有效的方法来完成它。

我有一个对象(一个采用 MKAnnotation 协议的 NSObject),它具有许多属性(标题、副标题、纬度、经度、信息等)。我需要能够将此对象传递给另一个对象,该对象希望使用 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 而不是对象作为键来检索信息。


4

6 回答 6

58

确定的事!使用 objc-runtime 和 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);
于 2012-04-25T15:19:29.637 回答
11

这是一篇旧文章,Richard J. Ross III 的回答确实很有帮助,但在自定义对象的情况下(自定义类中有另一个自定义对象)。但是,有时属性是其他对象等等,这使得序列化有点复杂。

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;

为了将这些类型的对象(多个自定义对象)转换为字典,我不得不稍微修改一下 Richard J. Ross III's Answer。

+(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];
}

我希望它会帮助某人。完全归功于 Richard J. Ross III。

于 2012-10-15T06:41:39.867 回答
5

如果属性与用于访问字典的键具有相同的名称,那么您可以只使用 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"];
于 2012-04-25T15:08:04.413 回答
2

为了完成 Richard J. Ross 的方法,这个方法与自定义对象的 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];
}
于 2014-03-07T18:53:51.570 回答
1

有这么多的解决方案,但没有什么对我有用,因为我有一个复杂的嵌套对象结构。这个解决方案从 Richard 和 Damien 那里得到了一些东西,但即兴发挥了 Damien 的解决方案与将键命名为类名有关。

这是标题

@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
于 2015-02-01T13:05:24.487 回答
0

您还可以使用NSObject+APObjectMappingGitHub 上提供的类别: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];
于 2015-02-22T13:03:18.840 回答