3
저는 Objective-c를 처음 사용했습니다.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
그리고 다음 코드로 방법을 실행
을 나는 KVC 지식을 연습 할 객체에 사전을 변환하는 간단한 방법을 쓰고 있어요-(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
}
내 질문에, 나는 (NSDate하지만 실제로 NSString이어야합니다) 잘못된 값으로 setValue : forKey : 통해 속성을 제공합니다. 하지만 예외가 발생하지 않는 이유는 런타임이나 Xcode에서 어떻게 dateTime 속성이 NSString 값을 허용 할 수 있습니까?
objc의 런타임에 유형 검사가 거의 없습니다. –