ios - 在方法objective-c之外保留数组数据
<p><p><strong>我有一个数组 <code>players</code>,其中包含两个字符串:<code>player1</code> 和 <code>player2</code>。这是我的 .h 文件:</strong></p>
<pre><code>#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
</code></pre>
<p><strong>数组在 viewDidLoad 中初始化,然后在我的 .m 文件中的两个 IBAction 中将数据输入到该数组中:</strong></p>
<pre><code>#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 = ;
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
;
;
//read player names to user defaults
stringForKey:@"player1"]];
stringForKey:@"player2"]];
self.players = [ init];
NSLog(@"%@",self.players);
}
- (void)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) {
[ postNotificationName:@"theChange" object:nil];
} else {
[ postNotificationName:@"theChange2" object:nil];
}
}
- (IBAction) returnKey1
{
player1 = ;
;
//set player1's name to user defaults
[ setValue: forKey:@"player1"];
}
- (IBAction) returnKey2
{
player2 = ;
;
//set player2's name to user defaults
[ setValue: forKey:@"player2"];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
;
return NO;
}
@end
</code></pre>
<p>如果我在第二个 IBAction 中使用 <code>NSLog</code>,一旦完成,该数组将正确显示在控制台中,并带有字符串 <code>player1</code> 和 <code>player2</code>,但是如果我尝试在其他任何地方使用该数组,它就是 <code>null</code>。谁能指出我正确的方向?</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>玩家有两个定义。</p>
<p>一个是属性。它从未初始化,因此为空。您将其用作 self.players 并由实例变量 _players 支持。</p>
<p>一个是实例变量。它在 viewDidLoad 中初始化。不是零。</p>
<p>这几乎肯定是个错误。</p></p>
<p style="font-size: 20px;">关于ios - 在方法objective-c之外保留数组数据,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/15459488/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/15459488/
</a>
</p>
页:
[1]