我是 Objective-c 的新手。我正在写一个简单的方法将字典转换为对象来练习KVC知识:
+(id) ConvertDictionary:(NSDictionary *)dict
ToClassInstance:(Class)type{
id targetObj = nil;
if(dict){
NSArray *dictKeys = dict.allKeys;
targetObj = [[type alloc] init];
for (NSString*item in dictKeys) {
[targetObj setValue:[dict objectForKey:item] forKey:item];
}
}
}
return targetObj;
}
还有一个简单的类:
#import <Foundation/Foundation.h>
@interface foo : NSObject
@property (nonatomic) int value;
@property(nonatomic,strong) NSDate *dateTime;
@end
并使用以下代码运行方法:
-(void)testConvert
{
NSArray *value = [NSArray arrayWithObjects:
[NSNumber numberWithInt:2],@"wrongDateString",nil];
NSArray *key = [NSArray arrayWithObjects:@"value",@"dateTime", nil];
NSDictionary *dict = [NSDictionary dictionaryWithObjects: value forKeys:key];
id result= [EPMClassUtility ConvertDictionary:dict
ToClassInstance:[foo class]];
foo *convert = (foo*) result;
NSLog(@"get value: %@",convert.dateTime);
//console write the line: get value:wrongDateString
}
我的问题是,我通过 setValue:forKey: 给属性一个错误类型的值(应该是 NSDate 但实际上是 NSString)。但是为什么没有异常发生在运行时或 XCode 中,属性 dateTime 如何接受 NSString 值?