我们可以使用NSMutable对象作为非NSMutable类的成员

时间:2011-05-06 18:45:08

标签: iphone objective-c nsmutabledictionary

假设我们有一个简单的NSDictionary类,它的一个对象可以是NSMutableDictionary对象吗?当我们在NSMutableDictionary对象中编辑值时,我们只编辑NSDictionary对象的值。由于我们没有编辑NSDictionary的对象,对于非可变NSDictionary类是否应该是一个问题?

1 个答案:

答案 0 :(得分:6)

集合类的可变性仅指能够整体修改集合,而不是成员。事实上,集合只包含指向它所包含对象的指针;他们的一切都没有改变。将对象放在不可变集合中不会改变对象自己的修改能力。

所以,是的,您可以毫不费力地修改NSMutableDictionary内的NSDictionary

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"

同样适用于任何不可变集合中包含的任何对象(允许修改):

@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"