ios - 在 "NSDictionary *"类型的对象上找不到写入字典元素的预期方法

标签 ios objective-c

+ (NSDateFormatter *) formatter : (NSString *) format  : (NSTimeZone*) timeZone  : (NSLocale *) locale {
    format = DefaultFormat;
    timeZone = [NSTimeZone localTimeZone];
    locale = [NSLocale currentLocale];
    NSString *hashKey = [NSString stringWithFormat:@"%lu%lu%lu", (unsigned long)format.hash, (unsigned long)timeZone.hash, (unsigned long)locale.hash];
    NSDictionary *formatters = [NSDate sharedDateFormatters];
    NSDateFormatter *cachedDateFormatter = formatters[hashKey];
    if (cachedDateFormatter != nil) {
        return cachedDateFormatter;
    }
    else {
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        formatter.dateFormat = format;
        formatter.timeZone = timeZone;
        formatter.locale = locale;
        formatters[hashKey] = formatter;
        return formatter;
    }

}

错误出现在这一行:formatters[hashKey] = formatter;

错误:在“NSDictionary *”类型的对象上找不到写入字典元素的预期方法

更多上下文:

+ (NSMutableDictionary<NSString *, NSDateFormatter *>*)sharedDateFormatters {
    static NSMutableDictionary *dict = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dict = [NSMutableDictionary new];
    });
    return dict;
}

最佳答案

您不能更新 NSDictionary 对象,因为它是不可变的。

编辑 由于显示了 sharedDateFormatters 的来源:

你只需要将 formatters 设为 NSMutableDictionary 而不是 NSDictionary,因为这是类方法返回的内容,然后代码将正常工作:

NSMutableDictionary *formatters = [NSDate sharedDateFormatters];

关于ios - 在 "NSDictionary *"类型的对象上找不到写入字典元素的预期方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36655773/

相关文章:

ios - Objective C 中两个数组中的字符串搜索

ios - 无法在iPhone 5s上安装应用

objective-c - 如何在 UITabBarController 中仅为一页添加 TTTableViewDragRefreshDelegate?

objective-c - 如何在 Objective-C (OS X) 中使用静态库?

用于请求桌面站点的 iOS 用户代理

ios - Twitter_OAuth 错误 : Domain=HTTP Code=410

objective-c - 如何获取 iPhone 的当前方向?

ios - 将函数转换为全局函数

ios - 如何在iOS中通过蓝牙获取配对设备列表?

ios - 当用户在 Swift 中购买游戏元素时,如何在我的游戏中减去硬币?