将数据从VC传递到VC和模型

时间:2015-05-18 07:24:53

标签: ios objective-c parameter-passing

我有一个levelViewController:

的.m

- (void)viewDidLoad {
[super viewDidLoad];


double delayTimeInSeconds = 2;
dispatch_time_t popTimeDelay = dispatch_time(DISPATCH_TIME_NOW, delayTimeInSeconds * NSEC_PER_SEC);
dispatch_after(popTimeDelay, dispatch_get_main_queue(), ^(void){
    //code to be executed after delay


    GameViewController *level1 = [self.storyboard instantiateViewControllerWithIdentifier:@"gameViewController"];

    level1.CARDS_PER_ROW = 6;
    level1.gameModel.NUMBER_OF_PAIRS = 3;

    [self presentViewController:level1 animated:NO completion:nil];


});//code to be executed after delay end

}
好吧,他现在提出了带有level1的GameViewController。 CARDS_PER_ROW在GameViewController.h中声明

·H

#import <UIKit/UIKit.h>
#import "GameModel.h"


@interface GameViewController : UIViewController  

@property (nonatomic) GameModel *gameModel;

@property (nonatomic) int CARDS_PER_ROW;
@property (nonatomic) NSInteger newGame;

@end

的.m

在我的ViewDidLoad中

self.gameModel = [[GameModel alloc] initWithNewGame:self.newGame];

对于我的GameViewController,我有我的GameModel:

·H

#import <Foundation/Foundation.h>

@interface GameModel : NSObject

@property (nonatomic) int NUMBER_OF_PAIRS;

-(id) initWithNewGame: (NSInteger)newGame;

@end

的.m

-(NSMutableArray *) createNewDeck {
NSMutableArray *cardDeck = [NSMutableArray array];

for (int i = 0; i < _NUMBER_OF_PAIRS; i++) {
    [cardDeck addObject:[[CardModel alloc] initWithValue:i]];
    [cardDeck addObject:[[CardModel alloc] initWithValue:i]];
}

return cardDeck;
}

确定。我的问题是:

我可以通过CARDS_PER_ROW。如果我定义NUMBER_OF_PAIRS(#define NUMBER_OF_PAIRS = x;)则可以。但我无法通过我的NUMBER_OF_PAIRS数据,我不知道为什么。此代码已发布,屏幕为空。

1 个答案:

答案 0 :(得分:0)

问题是此时gameModelnil。您已实例化控制器这一事实并不意味着它的view也已加载,视图将在首次访问时延迟加载。因此,您可以做的是将gameModel初始值设定项移动到控制器的初始化程序(如果是nib / storyboard实例化,则为-initWithCoder