Mutability
Mutability
- Subject: Mutability
- From: Norbert Heger <email@hidden>
- Date: Mon, 19 Nov 2001 19:07:32 +0100
Fortunately we now have real immutable collection classes (in 10.0 all
collection classes were mutable). Copying an immutable instance now simply
retains and returns the very same object, and invoking a mutating method
raises an exception.
But be aware of the fact, that even if an instance is immutable, it will be
a subclass of a mutable (abstract) superclass. Thus invoking [array
isKindOfClass:[NSMutableArray class]] will NOT tell you if the given array
is in fact mutable. Instead it always returns YES.
NSArray *immutableArray = [NSArray array];
NSArray *mutableArray = [NSMutableArray array];
NSLog(@"[immutableArray isKindOfClass:[NSMutableArray class]]: %d",
[immutableArray isKindOfClass:[NSMutableArray class]]);
// returns YES
NSLog(@"[immutableArray respondsToSelector:@selector(addObject:)]: %d",
[immutableArray respondsToSelector:@selector(addObject:)]);
// returns YES
NSLog(@"immutableArray:x copy:x",
immutableArray, [immutableArray copy]);
// returns the same object
NSLog(@"mutableArray:x copy:x",
mutableArray, [mutableArray copy]);
// returns a newly created object
NS_DURING
[immutableArray addObject:@""]; // raises an exception
NS_HANDLER
NSLog(@"%@ (%@)", [localException name], [localException reason]);
NS_ENDHANDLER
Best Regards, Norbert
_____________________________________________
Norbert Heger, Objective Development
http://www.obdev.at/