我有下面的代码片段:iOS - 区分NSDictionary和NSMutableDictionary?
NSString* value = @"value";
NSString* key = @"key";
NSMutableDictionary* foo = [NSMutableDictionary dictionary];
NSDictionary* bar = [NSDictionary dictionary];
NSAssert([bar isKindOfClass: [NSMutableDictionary class]], @""); // passes the assert as both are NSCFDictionary;
NSAssert([bar respondsToSelector: @selector(setValue:forKey:)], @""); // passes the assert because it NSCFDictionary does respond to the selector
[foo setValue:value forKey:key]; // no problem, foo is mutable
[bar setValue:value forKey:key]; // crash
所以,如果我有一个对象,或者是一个NSDictionary
或NSMutableDictionary
,短try块(我宁愿避免)的,我怎么能告诉区别?
你可能想要使用-setObject:forKey:,而不是-setValue:forKey :. – 2012-02-10 23:06:35
你有一个真实世界的例子,你什么时候有一本字典,但不确定它是否可变? – bneely 2012-02-10 23:15:45
只想添加[bar respondsToSelector:@selector(setValue:forKey :)]不起作用。 – picciano 2012-02-10 23:32:47