CIF*_*ter 19 iphone collections objective-c nsdictionary
我觉得这是一个愚蠢的问题,但无论如何我都会问...
我有一组NSDictionary对象,其键/值对对应于我创建的自定义类,调用它MyClass.有一种简单或"最佳实践"的方法让我基本上做MyClass * instance = [地图NSDictionary属性的事情MyClass ];吗?我有一种感觉,我需要做一些事情,NSCoding或者NSKeyedUnarchiver,而不是自己偶然发现,我认为那里的人可能能指出我正确的方向.
ret*_*unt 26
-setValuesForKeysWithDictionary:方法和-dictionaryWithValuesForKeys:是你想要使用的.
例:
// In your custom class
+ (id)customClassWithProperties:(NSDictionary *)properties {
return [[[self alloc] initWithProperties:properties] autorelease];
}
- (id)initWithProperties:(NSDictionary *)properties {
if (self = [self init]) {
[self setValuesForKeysWithDictionary:properties];
}
return self;
}
// ...and to easily derive the dictionary
NSDictionary *properties = [anObject dictionaryWithValuesForKeys:[anObject allKeys]];
Run Code Online (Sandbox Code Playgroud)
allKeysNSObject 上没有.你需要在NSObject上创建一个额外的类别,如下所示:
NSObject的+ PropertyArray.h
@interface NSObject (PropertyArray)
- (NSArray *) allKeys;
@end
Run Code Online (Sandbox Code Playgroud)
NSObject的+ PropertyArray.m
#import <objc/runtime.h>
@implementation NSObject (PropertyArray)
- (NSArray *) allKeys {
Class clazz = [self class];
u_int count;
objc_property_t* properties = class_copyPropertyList(clazz, &count);
NSMutableArray* propertyArray = [NSMutableArray arrayWithCapacity:count];
for (int i = 0; i < count ; i++) {
const char* propertyName = property_getName(properties[i]);
[propertyArray addObject:[NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding]];
}
free(properties);
return [NSArray arrayWithArray:propertyArray];
}
@end
Run Code Online (Sandbox Code Playgroud)
例:
#import "NSObject+PropertyArray.h"
...
MyObject *obj = [[MyObject alloc] init];
obj.a = @"Hello A"; //setting some values to attributes
obj.b = @"Hello B";
//dictionaryWithValuesForKeys requires keys in NSArray. You can now
//construct such NSArray using `allKeys` from NSObject(PropertyArray) category
NSDictionary *objDict = [obj dictionaryWithValuesForKeys:[obj allKeys]];
//Resurrect MyObject from NSDictionary using setValuesForKeysWithDictionary
MyObject *objResur = [[MyObject alloc] init];
[objResur setValuesForKeysWithDictionary:objDict];
Run Code Online (Sandbox Code Playgroud)