我有一个数组,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
。谁能给我指个正确的方向?
玩家有两个定义
1是一个属性。它从未初始化过,所以它是空的。你用它作为自我。玩家和实例变量_players.
One是一个实例变量。它在viewDidLoad中初始化。它不是nil
我会尝试将数组添加为私有实例变量,即将其添加到@interface中的.m文件中
NSMutableArray *players;
那么你应该能够通过使用"players"而不是self.players来访问数组。这应该在你的整个班级中都是可用的。如果这不起作用,那么我会说问题不在于你的变量的范围内,而是与其他一些代码。