我有一个数组players
,里面有两个字符串:player1
和player2
。这是我的.h文件:
#import <UIKit/UIKit.h>
@interface hardOne : UIViewController {
UISwitch *hard1ON;
NSMutableArray *players;
NSString *player1, *player2;
}
@property (nonatomic, retain) IBOutlet UISwitch *hard1ON;
@property (nonatomic) BOOL switchState;
@property (nonatomic, retain) NSMutableArray *players;
- (IBAction) switchValueChanged;
@end
数组在viewDidLoad中初始化,然后数据在我的.m文件的两个IBActions中输入到该数组中:
#import "hardOne.h"
@interface hardOne () <UITextFieldDelegate>
@property (nonatomic, strong) IBOutlet UITextField *textFieldOne;
@property (nonatomic, strong) IBOutlet UITextField *textFieldTwo;
@end
@implementation hardOne
@synthesize hard1ON;
@synthesize players;
@synthesize textFieldOne;
@synthesize textFieldTwo;
BOOL switchState;
int counter = 0;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[hard1ON setOn:switchState animated:NO];
//read player names to user defaults
[textFieldOne setText:[[NSUserDefaults standardUserDefaults] stringForKey:@"player1"]];
[textFieldTwo setText:[[NSUserDefaults standardUserDefaults] stringForKey:@"player2"]];
self.players = [[NSMutableArray alloc] init];
NSLog(@"%@",self.players);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction) switchValueChanged
{
counter += 1;
if (counter % 2 == 0) {
switchState = 0;
} else {
switchState = 1;
}
if (hard1ON.on) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"theChange" object:nil];
} else {
[[NSNotificationCenter defaultCenter] postNotificationName:@"theChange2" object:nil];
}
}
- (IBAction) returnKey1
{
player1 = [textFieldOne text];
[self.players addObject:(player1)];
//set player1's name to user defaults
[[NSUserDefaults standardUserDefaults] setValue:[textFieldOne text] forKey:@"player1"];
}
- (IBAction) returnKey2
{
player2 = [textFieldTwo text];
[self.players addObject:(player2)];
//set player2's name to user defaults
[[NSUserDefaults standardUserDefaults] setValue:[textFieldTwo text] forKey:@"player2"];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return NO;
}
@end
如果我在第二个IBAction中使用NSLog
,一旦完成,阵列就会在控制台中正确显示字符串player1
和player2
,但是如果我尝试使用其他任何地方的数组null
。有人能指出我正确的方向吗?
答案 0 :(得分:1)
你有两个玩家定义。
一个是财产。它从未被初始化,因此它是空的。您将它用作self.players并由实例变量_players支持。
一个是实例变量。它在viewDidLoad中初始化。这不是零。
这几乎肯定是一个错误。
答案 1 :(得分:0)
我会尝试将数组添加为私有实例变量,即将其添加到@interface中的.m文件中
NSMutableArray *players;
那么你应该能够通过使用“玩家”而不是自我玩家来访问数组。这应该是整个班级都可以使用的。如果这不起作用,那么我会说问题不在你的变量的范围内,而是与其他一些代码。