Ios 从另一个视图控制器使用可变数组

Ios 从另一个视图控制器使用可变数组,ios,nsmutablearray,Ios,Nsmutablearray,我四处寻找,找到了一些答案,但没有一个有效,我不知道我是否遗漏了什么。出于某种原因,惩罚.castigos以及playersView.players在代码中此时为零: 在GameViewController.m中: #import "SetPlayersViewController.h" #import "SetPunishmentsViewController.h" SetPlayersViewController *playersView = [[SetPlayersViewControl

我四处寻找,找到了一些答案,但没有一个有效,我不知道我是否遗漏了什么。出于某种原因,
惩罚.castigos
以及playersView.players在代码中此时为零:

在GameViewController.m中:

#import "SetPlayersViewController.h"
#import "SetPunishmentsViewController.h"

SetPlayersViewController *playersView = [[SetPlayersViewController alloc] init];
SetPunishmentViewController *Punish = [[SetPunishmentViewController alloc] init];
NSMutableArray *punishments = Punish.castigos;
NSMutableArray *playersOn = playersView.players;
int pickCard = arc4random() % numCards;
int playr = arc4random() % [playersOn count];//here is where i get EXC_ARITHMETIC(code=EXC = i386 DIV..)
int punsh = arc4random() % [punishments count];
@synthesize players;

//in view did load
players = [[NSMutableArray alloc] initWithObjects:@"A",@"B",nil];
在SetPlayerViewController.h中:

@interface SetPlayersViewController : UIViewController {
NSMutableArray *players;
}
@property (nonatomic,retain) NSMutableArray *players;
在SetPlayerViewController.m中:

#import "SetPlayersViewController.h"
#import "SetPunishmentsViewController.h"

SetPlayersViewController *playersView = [[SetPlayersViewController alloc] init];
SetPunishmentViewController *Punish = [[SetPunishmentViewController alloc] init];
NSMutableArray *punishments = Punish.castigos;
NSMutableArray *playersOn = playersView.players;
int pickCard = arc4random() % numCards;
int playr = arc4random() % [playersOn count];//here is where i get EXC_ARITHMETIC(code=EXC = i386 DIV..)
int punsh = arc4random() % [punishments count];
@synthesize players;

//in view did load
players = [[NSMutableArray alloc] initWithObjects:@"A",@"B",nil];

这是因为UIViewController的延迟初始化

只有在有人调用view属性后,才会加载
UIViewController
的视图。 因此,只有在有人调用view属性之后才会调用
viewDidLoad
方法


你应该在视图控制器f.e.的
init
方法中初始化你的数组。

你在
viewDidLoad
中实例化
players
,当你访问可变数组时,视图很可能没有加载。只需在
initWithNibName:bundle:
中alloc/init数组。请参阅我的答案,它描述了viewcontroleer、view controller life cyclewait中的调用顺序,所以我有点迷路了。我必须添加什么代码以及在哪里?您是否在视图控制器中创建了init方法?将玩家数组的初始化放在该方法中读取问题是NSMutableArray中的push.castigos*pumpions=pump.castigos;是nil,我不明白您希望我在init方法中初始化什么,而且我忘了指定GameViewController中的代码。h是一个只需按一下按钮即可调用的方法,而不是ViewDidLoad