Search code examples
iosobjective-cnsmutabledictionary

static NSMutableDictionary can only store one object


I tried creating a static NSMutableDictionary like this

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;
}

It seems I can only add one object to the dictionary but I believe I took care of creating a new one each time so I am stuck on why it seems I am only able to store one object in this dictionary. Also, it adds the first one and fails to add any subsequent calls.


Solution

  • From given part of code it is too hard to say what happening with you Textures static variable (it may be multithread problem, or event the same name value for each run), so I can suggest you to use following approach to fix problem:

    + (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;
    }