【发布时间】:2013-03-05 18:23:17
【问题描述】:
我有一个数组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
如果我在第二个 IBAction 中使用 NSLog,一旦完成,该数组将在控制台中正确显示字符串 player1 和 player2,但是如果我尝试在其他任何地方使用该数组null。谁能指出我正确的方向?
【问题讨论】:
-
您的班级中如何定义
player1和player2?如果将它们存储到数组中,为什么还需要这些属性?此外,通常建议使用self.访问属性,例如self.players = ...。 -
你在其他地方是什么意思?请为整个 .h 和 .m 文件添加代码。另外,你在使用 ARC
-
想想你是对的,它们是不必要的变量。怎么这么好?无论哪种方式,
player1和player2变量都不会影响数组在其他方法中变为 null,对吗? -
是的,我正在使用 ARC。我现在将更新代码。例如,如果我在 viewDidLoad 设置后尝试
NSLog数组,它会显示为null。我这样做的原因是因为我试图从另一个类访问players数组以获取SearchViewController。 -
Yoy 可能会再次分配播放器类...那就是 y
标签: ios objective-c methods nsmutablearray