2017-06-19 69 views
0

我试图创建一个静态的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; 
} 

看来我只能一个对象添加到字典中,但我相信我把每一个时间,所以创建一个新的护理我被困在为什么看来我只能在这本字典中存储一个对象。此外,它添加了第一个,并且未能添加任何后续调用。

+0

可能不是主要问题,但这不是线程安全的。是否有一个原因,你使用'纹理'的延迟初始化,而不是在加载类时急切地实例化呢? – Alexander

+0

我从来没有初始化类,它只是一个静态方法,当我添加另一个纹理时,我只是再次调用该方法 –

+0

什么表示只能添加一个对象?后续尝试失败的原因是什么? –

回答

2

从给定的代码部分来说,很难说出什么发生在你身上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; 
} 
+0

我试过了,仍然得到了相同的结果 –

+0

你可以发布多一点你的代码吗? – toma