2013-03-27 2 views
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 값을 허용 할 수 있습니까?

+0

objc의 런타임에 유형 검사가 거의 없습니다. –

답변

2

objective-c에 대한 자동 런타임 유형 검사가없고 setValue:frorKey:을 사용하면 값 인수가 모든 유형 일 수 있기 때문에 컴파일 타임 검사를 피할 수 있습니다.

런타임 유형 검사를 원할 경우 런타임에 유형을 확인하는 사용자 고유의 -setDateTime: (예)을 구현해야합니다.