我有下面的代碼片段: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