【问题标题】:NSMutableDictionary class attribute is not modified in methodNSMutableDictionary 类属性未在方法中修改
【发布时间】:2014-02-23 15:13:33
【问题描述】:

具有以下具有 NSMutableDictionary* 属性的类

@interface MyClass : NSObject
@property(retain,atomic) NSMutableDictionary* dict;
- (void) method;
@end

- (id) init{
    self = [super init];
    if(self){
        self.dict = [NSMutableDictionary dictionary];
    }

    return self;
}
- (void) method
{
    NSMutableDictionary*  dict = [NSMutableDictionary dictionary];
    self.dict[@"Test"] = @"Shmest";
    dict[@"Test"] = @"Shmest";
    NSLog(@"Count: %ld",[self.dict allKeys].count);
    NSLog(@"Count: %ld",[dict allKeys].count);
}

输出是

2014-02-23 19:05:44.110 MyProj[12818:303] Count: 0
2014-02-23 19:05:44.110 MyProj[12818:303] Count: 1

为什么 self.dict 没有被修改?

UPD 使用MyClass * obj = [MyClass alloc] 而不是MyClass * obj = [[MyClass alloc] init],所以init 没有被调用。

【问题讨论】:

  • 你在任何地方设置 self.dict 吗?在为 dict 属性设置值之前,它将为 nil,因此其行为就像在您的代码中一样。
  • 我在 init 方法中设置(添加到帖子正文)
  • 将 NSLog(dict) 添加到 method 以检查 to 是否已初始化。
  • 它没有初始化,我的错。使用MyClass * obj = [MyClass alloc] 而不是MyClass * obj = [[MyClass alloc] init];非常感谢! `

标签: objective-c nsmutabledictionary


【解决方案1】:

需要实例化dict属性,这可以在init方法中完成。

示例:

- (instancetype)init {
    self = [super init];
    if (self) {
        _dict = [NSMutableDictionary new];
    }
    return self;
}

致电:

MyClass *myClass = [MyClass new];
[myClass method];

【讨论】:

  • 请看一下我添加到帖子中的init 方法。有什么不对? (new、dictionary 和 alloc 的行为方式相同:不会将新值添加到 dict)
  • 我刚刚测试了你的代码,它可以工作。我确实必须添加@implementation MyClass 和结尾@end。
猜你喜欢
  • 2019-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-02
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
相关资源
最近更新 更多