Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Mutability



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:%08x copy:%08x",
immutableArray, [immutableArray copy]);
// returns the same object

NSLog(@"mutableArray:%08x copy:%08x",
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/




Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.