NSMutableDictionary is being treated as an NSDictionary
I have a simple class with an NSMutableDictionary member variable. However, when I call setObject:forKey I get an error ('mutating method sent to immutable object'). The source of the problem is obvious from the debugger -- my NSMutableDictionary is actually of type NSDictionary.
I must be missing something incredibly simple but can't seem to fix it. Here is the relevant code:
// Model.h
@interface Model : NSObject {
NSMutableDictionary *piers;
}
@property (nonatomic,retain) NSMutableDictionary *piers;
@end
// Model.m
@implementation Model
@synthesize piers;
-(id) init {
if (self = [super init]) {
self.piers = [[NSMutableDictionary alloc] initWithCapacity:2];
[self createModel];
}
return self;
}
-(void) cr开发者_开发问答eateModel {
[piers setObject:@"happy" forKey:@"foobar"];
}
@end
If I put a breakpoint anywhere in the code and investigate self.piers, it is of type NSDictionary. What am I missing so that it is treated as an NSMutableDictionary instead? Thanks!
Your code works for me without any modification. I made a Foundation based command line tool (Mac OS X) with this code:
#import <Foundation/Foundation.h>
// Model.h
@interface Model : NSObject {
NSMutableDictionary *piers;
}
@property (nonatomic,retain) NSMutableDictionary *piers;
-(void) createModel;
@end
// Model.m
@implementation Model
@synthesize piers;
-(id) init {
if (self = [super init]) {
self.piers = [[NSMutableDictionary alloc] initWithCapacity:2];
[self createModel];
}
return self;
}
-(void) createModel {
[piers setObject:@"happy" forKey:@"foobar"];
}
@end
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// insert code here...
Model *model = [[Model alloc] init];
NSLog(@"Model: %@", [model.piers objectForKey:@"foobar"]);
[pool drain];
return 0;
}
and it gave me the expected output:
2010-04-06 12:10:19.510 Model[3967:a0f] Model: happy
As KennyTM says, your use of self is a little wrong. in your init
, the general pattern is
NSMutableDictionary *aPiers = [[NSMutableDictionary alloc] initWithCapacity:2];
self.piers = aPiers;
[aPiers release];
Later on in the code, you should be using self.piers
.
Try making a project like mine and see if the problem still exists. You'll probably find that the problem is somewhere else.
Try remove the self.
.
piers = [[NSMutableDictionary alloc] initWithCapacity:2];
In ObjC, the notation
obj.prop = sth;
is equivalent to
[obj setProp:sth];
which has totally different semantic than
obj->prop = sth;
Although highly unlikely, probably your mutable dictionary becomes immutable during the -setPiers:
procedure. Just say No to self.anything
(until you understand how property works).
精彩评论