Skip to content

Instantly share code, notes, and snippets.

@stevestreza
Created March 23, 2009 20:49
Show Gist options
  • Save stevestreza/83769 to your computer and use it in GitHub Desktop.
Save stevestreza/83769 to your computer and use it in GitHub Desktop.
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// insert code here...
NSDictionary *immutable = [[NSDictionary alloc] init];
NSMutableDictionary *mutable = [[NSMutableDictionary alloc] init];
NSLog(@"Classnames: %@ and %@",[immutable className], [mutable className]);
//test respondsToSelector for setObject:forKey:
if([immutable respondsToSelector:@selector(setObject:forKey:)]){
NSLog(@"immutable responds to setObject:forKey:");
}
if([mutable respondsToSelector:@selector(setObject:forKey:)]){
NSLog(@"mutable responds to setObject:forKey:");
}
//test against NSMutableDictionary's class
if([immutable isKindOfClass:[NSMutableDictionary class]]){
NSLog(@"immutable is a mutable dict");
}
if([mutable isKindOfClass:[NSMutableDictionary class]]){
NSLog(@"mutable is a mutable dict");
}
[pool drain];
return 0;
}
NSCFDictionaryTest[34961:10b] Classnames: NSCFDictionary and NSCFDictionary
NSCFDictionaryTest[34961:10b] immutable responds to setObject:forKey:
NSCFDictionaryTest[34961:10b] mutable responds to setObject:forKey:
NSCFDictionaryTest[34961:10b] immutable is a mutable dict
NSCFDictionaryTest[34961:10b] mutable is a mutable dict
// this works, although it requires exceptions
BOOL DictIsMutable(NSDictionary *dict){
BOOL isMutable = YES;
@try {
id oldValue = ([dict objectForKey:@"SSMutabilityTest"]);
[dict setObject:@"foo" forKey:@"SSMutabilityTest"];
//if immutable, it will throw an exception
if(oldValue) [dict setObject:oldValue forKey:@"SSMutabilityTest"];
}
@catch (NSException * e) {
isMutable = NO;
}
return isMutable;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment