objective-c - NSMutableDictionary 被视为 NSDictionary

标签 objective-c cocoa nsdictionary nsmutabledictionary

我有一个带有 NSMutableDictionary 成员变量的简单类。但是,当我调用 setObject:forKey 时,出现错误(“将方法发送到不可变对象(immutable对象)”)。问题的根源从调试器中显而易见——我的 NSMutableDictionary 实际上是 NSDictionary 类型。

我一定错过了一些非常简单的东西,但似乎无法修复它。相关代码如下:

// 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) createModel {
 [piers setObject:@"happy" forKey:@"foobar"];  
}
@end

如果我在代码中的任何位置放置断点并调查 self.piers,它的类型为 NSDictionary。我缺少什么才能将其视为 NSMutableDictionary ?谢谢!

最佳答案

您的代码无需任何修改即可为我工作。我用以下代码制作了一个基于基础的命令行工具(Mac OS X):

#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;
}

它给了我预期的输出:

2010-04-06 12:10:19.510 模型[3967:a0f]模型:快乐

正如KennyTM所说,你对 self 的使用有点错误。在您的 init 中,一般模式是

NSMutableDictionary *aPiers = [[NSMutableDictionary alloc] initWithCapacity:2];
self.piers = aPiers;
[aPiers release];

稍后在代码中,您应该使用 self.piers

尝试制作一个像我这样的项目,看看问题是否仍然存在。您可能会发现问题出在其他地方。

关于objective-c - NSMutableDictionary 被视为 NSDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2583305/

相关文章:

cocoa - 覆盖 NSTextField 中 NSButton 的等效键

xcode - 将数据添加到 plist 文件时出现问题

objective-c - 如何将 NSdictionaries 的 NSarray 转换为 XML 文件?

objective-c - Cocoa 中的本地对象作用域和内存管理

ios - 从 Assets 库的图像 url 代表转到 base64

objective-c - 在 iPhone/iPad 上存储数据

objective-c - NSDictionary objectForKey 返回值

iOS: subview Controller 和自动布局

objective-c - 将 NSNumber 对象分配给 NSString 对象不会导致任何错误或警告

swift - 存储工作 TableView Controller 的窗口大小