简体   繁体   中英

Objective-C KVC changes the type of property

I'm new to Objective-c. I'm writing a simple method to convert a dictionary to a object to practice the KVC knowledge:

+(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;
}

And a simple class:

 #import <Foundation/Foundation.h>
 @interface foo : NSObject
 @property (nonatomic) int value;
 @property(nonatomic,strong) NSDate *dateTime;
 @end

And run the methods with following code:

-(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

}

My question is, I give a value with wrong type(should be NSDate but actually be NSString) to the property through setValue:forKey:. But why there is no exception occurs runtime or in XCode and how can the property dateTime accept the NSString value?

There is no automatic run-time type checking for objective-c, and using setValue:frorKey: avoids over any compile-time checking because the value argument can be of any type.

If you want run-time type checking, you will need to implement your own -setDateTime: (as an example) that checks the type at run time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM