假设我们有一个简单的NSDictionary
类,它的一个对象可以是NSMutableDictionary
对象吗?当我们在NSMutableDictionary
对象中编辑值时,我们只编辑NSDictionary
对象的值。由于我们没有编辑NSDictionary
的对象,对于非可变NSDictionary
类是否应该是一个问题?
答案 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"