1:将字典中的键值对赋值给对象的各个成员变量。关键字:
setValuesForKeysWithDictionary1.1先定义一个类,该类为Quotation 声明如下:
@interface Quotation : NSObject {
} @property (nonatomic, retain) NSString *character; @property (nonatomic, assign) NSInteger act; @property (nonatomic, assign) NSInteger scene; @property (nonatomic, retain) NSString *quotation;
@end
@implementation Quotation
@synthesize character, act, scene, quotation; - ( void)dealloc { [character release]; [quotation release]; [super dealloc]; } @end
1.2 然后自动从字典中将值取到对象中。使用了“setValuesForKeysWithDictionary”这么一个函数,代码如下:
NSArray *quotationDictionaries = [playDictionary objectForKey:@"quotations"];
NSMutableArray *quotations = [NSMutableArray arrayWithCapacity:[quotationDictionaries count]]; for (NSDictionary *quotationDictionary in quotationDictionaries) { Quotation *quotation = [[Quotation alloc] init]; [quotation setValuesForKeysWithDictionary:quotationDictionary]; [quotations addObject:quotation]; [quotation release];
}