【问题标题】:Singleton dictionary is empty, and I don't see why单例字典是空的,我不明白为什么
【发布时间】:2016-12-08 20:26:49
【问题描述】:

我有一个 iOS 应用程序,它将传入的文本字段与用于导入记录的 标准 字段相匹配。我的问题是使用这些字段的 NSMutableDictionary 是空的!这是保存映射的代码:

-(void)mapUserFields: (id) sender  {   //  move contents of each textField when user has finished entering it

    SingletonDictionary *sd = [SingletonDictionary sharedDictionary];

    UITextField *tf = (UITextField *)sender;  //  textfield contains the pointer to user's half of the equation
    int tagValue = (int)tf.tag;  //  get the tag value

    [sd.dictionaryOfUserIndexes setObject:tf.text forKey:[NSString stringWithFormat:@"%d", tagValue]];  //  value found in textField id'd by tag

    NSLog(@"\nfield.text: %@  tagValue: %d  nsd.count: %d\n",tf.text, tagValue, sd.dictionaryOfUserIndexes.count);

}

这是 NSLog 的结果:

field.text: 1 tagValue: 38 nsd.count: 0

这是.h文件中单例的定义:

@property (nonatomic, retain) NSMutableDictionary *dictionaryOfUserIndexes;

这是在.m文件中初始化单例的代码:

//--  SingletonDictionaryOfUserIDs  --
+ (id) sharedDictionary  {

    static dispatch_once_t dispatchOncePredicate = 0;
    __strong static id _sharedObject = nil;
    dispatch_once(&dispatchOncePredicate, ^{
        _sharedObject = [[self alloc] init];
    });

    return _sharedObject;
}

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

@end

我相信我的问题是因为 sd.dictionaryOfUserIndexes 没有初始化,但我不确定这是不是真的,如果是这样,如何初始化它(我尝试了几种不同的变体,所有这会产生构建错误)。我查看了 SO 和 Google,但没有发现任何解决此特定问题的方法。非常感谢您的帮助!

【问题讨论】:

  • 显示dictionaryOfUserIndexes 在你的单例类中是如何声明的。请格式化您的代码。您发布的问题太多,无法发布格式错误的代码。
  • re: 格式化我的代码更好吗?如果不是,我不明白你指的是什么...请详细说明... SD
  • SingletonDictionary 继承自什么?
  • mapUserFields 中的第一行...现在我看了一下,也不确定这是否正确...这是我几年前写的,现在回头看,可以'不记得我为什么做这些事情......当时只是在学习单身......

标签: objective-c singleton ios9 xcode8


【解决方案1】:

我们可以在这段代码中改进一些地方,但唯一错误是在init 方法中对dictionaryOfUserIndexes 的引用。发布的代码不会编译,除非:(a) 你有这样一行:

@synthesize dictionaryOfUserIndexes = dictionaryOfUserIndexes;

这样后备变量的命名就没有默认的_ 前缀,或者 (b) 您使用默认前缀引用 ivar,如下所示:

_dictionaryOfUserIndexes = [NSMutableDictionary new];

另一种方法——除了在 init 方法中之外,在大多数情况下都更可取——是使用综合设置器,例如:

self.dictionaryOfUserIndexes = [NSMutableDictionary new];

但仅通过该更改(因此它将编译)您的代码运行良好,向字典添加一个值并记录一个递增的计数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-15
    • 1970-01-01
    • 1970-01-01
    • 2011-08-05
    • 2019-04-21
    • 2010-11-08
    • 2013-02-20
    • 2022-12-14
    相关资源
    最近更新 更多