我有一个数组,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 文件中的两个 IBAction 中将数据输入到该数组中:
#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    
如果我NSLog在第二个 IBAction 中使用,一旦完成,该数组将在控制台中正确显示字符串player1和player2,但是如果我尝试在其他任何地方使用该数组,它是null。谁能指出我正确的方向?