3
我是Objective-c的新手。我正在寫一個簡單的方法來字典轉換爲對象來練習KVC知識: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值?
在運行時中(幾乎)沒有類型檢查objc – 2013-03-27 09:23:41