Reputation: 31
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?
Upvotes: 3
Views: 367
Reputation: 17481
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.
Upvotes: 2