开发者

Can we use NSMutable objects as members of a non-NSMutable class

Suppose we have simple NSDictionary class, can one of its objects be an NSMutableDictionary object? When we edit a value within th开发者_如何学JAVAe NSMutableDictionary object, we are only editing values of the object of NSDictionary. Since we are not editing the object of NSDictionary, should it be a problem for the non-mutable NSDictionary class?


The mutability of a collection class refers only to the ability to modify the collection as a whole, not the members. The collection in fact just consists of pointers to the objects it contains; nothing about them is changed. Putting an object inside an immutable collection does not change the object's own ability to be modified.

So, yes, you can modify an NSMutableDictionary inside an NSDictionary, without difficulty.

NSDictionary * myDict;
myDict = [NSDictionary dictionaryWithObject:
            [NSMutableDictionary dictionaryWithObject:@"This is one string"
                                               forKey:@"sampleKey"]
                                     forKey:@"mutableDict"];

NSMutableDictionary * myMutableDict = [myDict objectForKey:@"mutableDict"];

NSLog(@"%@", [myMutableDict objectForKey:@"sampleKey"];
// Prints "This is one string"

[[myDict objectForKey:@"mutableDict"] setObject:@"Not the same as before" 
                                         forKey:@"sampleKey"];

NSLog(@"%@", [myMutableDict objectForKey:@"sampleKey"];    
// Prints "Not the same as before"

Likewise for any object (which allows modification) contained inside any immutable collection:

@interface MyNeatObjectClass : NSObject {
        NSString * neatString;
}

- (id)initWithNeatString:(NSString *)initialString;
- (void)setNeatString:(NSString *)newString;
- (NSString *)neatString;

MyNeatObjectClass * myObj = [[MyNeatObjectClass alloc] 
                                         initWithNeatString:@"Example string"];

NSLog(@"%@", [myObj neatString]);    // Prints "Example string"
NSArray * arr = [NSArray arrayWithObject:myObj];
[myObj release];

// instance of MyNeatObjectClass
[[arr objectAtIndex:0] setNeatString:@"Another string"];
NSLog(@"%@", [[arr objectAtIndex:0] neatString]);     // Prints "Another string"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜