ios - static NSMutableDictionary 只能存储一个对象

标签 ios objective-c nsmutabledictionary

我试着像这样创建一个静态的 NSMutableDictionary

static NSMutableDictionary* Textures;

+(Texture*) loadTexture: (NSString*) name path: (NSString*) path{
    CGImageRef imageReference = [[UIImage imageNamed:path] CGImage];

    GLKTextureInfo* textureInfo = [GLKTextureLoader textureWithCGImage:imageReference options:nil error:NULL];

    Texture* texture = [[Texture alloc] init:textureInfo];

    if(!Textures) Textures = [[NSMutableDictionary alloc] init];

    [Textures setObject:texture forKey:name];

    return texture;
}

似乎我只能将一个对象添加到字典中,但我相信我每次都会创建一个新对象,所以我对为什么我似乎只能在该字典中存储一个对象感到困惑。此外,它会添加第一个调用,但不会添加任何后续调用。

最佳答案

从给定的代码部分很难说出你发生了什么 Textures 静态变量(它可能是多线程问题,或者每个事件的 name 值相同运行),因此我建议您使用以下方法来解决问题:

+ (NSMutableDictionary *) textures {
    static NSMutableDictionary *result = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        result = [NSMutableDictionary new];
    });
    return result;
}

+ (Texture*) loadTexture: (NSString*) name path: (NSString*) path {
    CGImageRef imageReference = [[UIImage imageNamed:path] CGImage];

    GLKTextureInfo* textureInfo = [GLKTextureLoader textureWithCGImage:imageReference options:nil error:NULL];

    Texture* texture = [[Texture alloc] init:textureInfo];

    self.textures[name] = texture;

    return texture;
}

关于ios - static NSMutableDictionary 只能存储一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44637886/

相关文章:

ios - 由于未捕获的异常 'NSInvalidArgumentException',我的 Xcode 应用程序在尝试实现 NSFetchedResultsController 后崩溃

java - Objective-C 相当于 Java "protected"修饰符

swift - NSMutableDictionary 路径 "unexpectedly found nil while unwrapping an Optional value"

ios - 如何在 viewDidLoad() Swift2 中初始化变量

ios - 如果松开第一个手指,UIView touchesMoved 不会被调用

ios - 为什么数据给我空值?

ios - 如何添加位于 NSMutableDictionary 和 NSArray 属性内的 NSArray 对象?

ios - 无法将 NSArray 中的所有数据存储到 NSMutableDictionary 中?

objective-c - 无法移动我的 UIScrollView

iphone - objective-c 对 NSStrings 的 NSMutableSet 进行排序?