0

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.

  • Might not be the main issue, but this isn't thread safe. Is there a reason you're using lazy initialization of `Textures`, rather than instantiating it eagerly when the class is loaded? – Alexander Jun 19 '17 at 18:54
  • I never initialize the class it's just a static method and when I add another texture I just call the method again – Austin Twining Jun 19 '17 at 18:59
  • What is the indication that you can only add one object? How is it failing on subsequent attempts? – Chris Edgington Jun 19 '17 at 19:03
  • 1
    You may not initialize any objects of this class, but the class itself does get initialized when it's loaded into the objective C runtime. You can override the `+initialize` method to perform any class initialization you need, such as creating this dict https://stackoverflow.com/a/27859968/3141234 – Alexander Jun 19 '17 at 19:14
  • Diagnose with `NSLog(@"adding key %@ to dictionary with pointer %p", name, Textures);` – danh Jun 19 '17 at 21:04

1 Answers1

3

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;
}
toma
  • 1,471
  • 12
  • 20