我试着像这样创建一个静态的 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/