我编码使用Cocos2D框架的Objective-C,我有一个单身人士用于多种目的。一个新的目的是获取和设置角色的字符串“状态”。我最近为此目的创建了一个NSDictionary,但是我在调用单例内部的一个方法时遇到了程序冻结的问题。NSMutableDictionary单身人士问题
这里是单例代码。我只是留在人物状态的东西:
.H
@interface ExGlobal : NSObject {
NSArray *charStates_keys;
NSArray *charStates_objects;
NSMutableDictionary *charStates;
}
@property(nonatomic, retain) NSMutableDictionary *charStates;
+(ExGlobal*)sharedSingleton;
- (NSString *)charState:(NSString *)charName;
- (void)set_charState:(NSString *)value forCharName:(NSString *)charName;
@end
.M
#import "ExGlobal.h"
@implementation ExGlobal
@synthesize charStates;
static ExGlobal* _sharedSingleton = nil;
+(ExGlobal*)sharedSingleton {
@synchronized([ExGlobal class]) {
if (!_sharedSingleton) {
[[self alloc] init];
}
return _sharedSingleton;
}
return nil;
}
+(id)alloc {
@synchronized([ExGlobal class]) {
NSAssert(_sharedSingleton == nil, @"Attempted to allocate a second instance of a singleton.");
_sharedSingleton = [super alloc];
return _sharedSingleton;
}
return nil;
}
-(id)init {
self = [super init];
if (self != nil) {
// initialize stuff here
exitName = @"ruinsSkyMid";
sceneChangeKind = @"reborn";
charStates = [[NSMutableDictionary alloc] init];
charStates_keys = [NSArray arrayWithObjects:@"Feathers", @"Hummus", nil];
charStates_objects = [NSArray arrayWithObjects:@"at wall", @"with Feathers", nil];
charStates = [NSMutableDictionary dictionaryWithObjects:charStates_objects forKeys:charStates_keys];
}
return self;
}
- (NSString *)charState:(NSString *)charName{
NSString *value = [charStates objectForKey:charName];
return value;
}
- (void)set_charState:(NSString *)charState forCharName:(NSString *)charName{
[charStates setObject:charState forKey:charName];
}
- (void)dealloc {
//I know it doesn't get called, but just in case
[charStates release];
[super dealloc];
}
@end
这是我不清楚究竟是什么问题时,它冻结。当发生这种情况时,我在控制台中得到的全部内容为:
Program received signal: “EXC_BAD_ACCESS”.
warning: Unable to read symbols for /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.3.5 (8L1)/Symbols/Developer/usr/lib/libXcodeDebuggerSupport.dylib (file not found).
Previous frame inner to this frame (gdb could not unwind past this frame)
Previous frame inner to this frame (gdb could not unwind past this frame)
我确定无法找到问题。我发现如果我在charState和set_charState方法内重新定义了charStates_keys,charStates_objects和charStates,它似乎无冻结地工作,除了set_charState不改变状态。
感谢编程语法的东西..但我怎么不保留它? – VagueExplanation
我也试过charStates = [[NSMutableDictionary alloc] retain];这里有些困惑。 – VagueExplanation
另外在我的理解,dictionaryWithObjects是autoreleased字典,所以我甚至不必保留它在第一个地方,对吧? – VagueExplanation