不确定我在这里做错了什么。当我尝试通过特定键或所有键检查字典时,我得到错误或null。 (我知道我正在使用一个字符串,我可以使用布尔值作为条件我就像检查那样说真或假而不是YES和NO。将它添加到我的OCD列表。:D)activePlayer设置在awakeFromNib方法中,可以使用P1和P2之间的弹出按钮进行切换。
- (IBAction)setPlayer:(id)sender {
haserror = @"false";
errmsg = [NSMutableString stringWithCapacity:0];
[errmsg retain];
[errmsg appendString: @"There was a problem setting your team up\n\n"];
thisTeamName = [txtTeamName stringValue];
thisTeamColor = [pdTeamColor itemTitleAtIndex:[pdTeamColor indexOfSelectedItem]];
//validate form
if ([thisTeamName isEqualToString:@""]) {
haserror = @"true";
[errmsg appendString: @"You must enter a team name\n\n"];
}
if ([thisTeamColor isEqualToString:@"Select A Color"]) {
haserror = @"true";
[errmsg appendString: @"You must select a team color\n\n"];
}
//check for errors
if (haserror == @"true") {
[self showAlert: errmsg];
} else {
//set up treasury
treasury = 1000;
//convert to string for display
[lblTreasury setStringValue: [NSString stringWithFormat:@"$%i", treasury] ];
//add items to dictionary
if (activePlayer == @"1") {
[p1TeamData setObject:thisTeamName forKey:@"teamName"];
[p1TeamData setObject:thisTeamColor forKey:@"teamColor"];
[p1TeamData setObject:[NSString stringWithFormat:@"%i", treasury] forKey:@"cash"];
} else {
[p2TeamData setObject:thisTeamName forKey:@"teamName"];
[p2TeamData setObject:thisTeamColor forKey:@"teamColor"];
[p2TeamData setObject:[NSString stringWithFormat:@"%i", treasury] forKey:@"cash"];
}
NSLog(@"%@", [p1TeamData allKeys]);
}
[errmsg release];
}
[编辑:这是.h文件]
@interface GameController :NSObject {
IBOutlet id btnSaveData;
IBOutlet id lblTreasury;
IBOutlet id pdPickPlayer;
IBOutlet id pdTeamColor;
IBOutlet id txtTeamName;
int activePlayer;
NSString* activePlayerName;
NSString* activePlayerTeamColor;
int treasury;
NSMutableDictionary* p1TeamData;
NSMutableDictionary* p2TeamData;
NSArray* players;
NSArray* teamColors;
NSArray* unittypes;
NSString* thisTeamName;
NSString* thisTeamColor;
NSMutableString* errmsg;
NSString* haserror;
}
- (void)awakeFromNib; - (IBAction)getPlayer:(id)sender; - (IBAction)setPlayer:(id)sender; - (void)showAlert:(NSMutableString *)m; @end
答案 0 :(得分:4)
确保使用-initXXX
方法初始化集合。如果没有,他们将被分配到nil
。
-(id)initXXX:... {
if ((self = [super initYYY:...])) {
...
p1TeamData = [[NSMutableDictionary alloc] init];
p2TeamData = [[NSMutableDictionary alloc] init];
...
}
return self;
}
如果你想要的只是“真”和“假”,那就自己定义吧。这不是使用字符串而不是BOOL的原因。事实上,除了YES和NO。
之外,基金会已经定义了TRUE和FALSE另外,请使用activePlayer
的整数。
您应该始终将NSString与-isEqualToString:
进行比较,而不是==
。
if ([haserror isEqualToString:@"true"])
...
if ([activePlayer isEqualToString:@"1"])
这应该是p1TeamData
始终为零的原因,因为activePlayer == @"1"
不可靠,并且可能会将玩家1的内容分配给p2TeamData
。