0

我有两个视图控制器:BSViewController其中包含源 ivarsnumberarray,以及 BSotherViewController作为目标需要接收 ivars 。(BSViewController上面有一个按钮,用于连接BSotherViewController。)

如何访问两个 ivars 中的值BSotherViewController

BSViewController.h

#import <UIKit/UIKit.h>

@interface BSViewController : UIViewController
@property (nonatomic) NSInteger number;
@property (nonatomic, weak) NSArray * array;
@end

BSViewController.m

#import "BSViewController.h"

@interface BSViewController ()
@end
@implementation BSViewController
@synthesize number;
@synthesize array;

- (void)viewDidLoad
{
    [super viewDidLoad];
    BSViewController *view = [[BSViewController alloc] init];
    NSArray*  _array = [NSArray arrayWithObjects: @"manny",@"moe",nil];
    view.array = _array;
    view.number = 25;
}

@end

BSotherViewController.h

#import <UIKit/UIKit.h>

@class BSViewController;
@interface BSotherViewController : UIViewController
@end

BSotherViewController.m

下面的问题aview.number是0,不是25;并且aview.array为空。

#import "BSotherViewController.h"
#include "BSViewController.h"
@interface BSotherViewController ()

@end

@implementation BSotherViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    BSViewController *aview = [[BSViewController alloc] init];
    NSLog(@"other view: %@", aview);
    NSLog(@"other number: %d", aview.number);  // produces 0, not desired 25
    NSLog(@"other array: %@", aview.array);    // produces null, not desired manny,moe
}
@end
4

2 回答 2

1

当您实例化BSViewControllerfrom时,BSOtherViewController您正在调用 init 方法。这些值在viewDidLoadin 中设置BSViewController,并且在实际加载视图之前不会调用该方法。

尝试覆盖 init 方法并设置值

- (id)init {

if (self = [super init]) {
    //Set values
     NSArray*  _array = [NSArray arrayWithObjects: @"manny",@"moe",nil];
     self.array = _array;
     self.number = 25;
}
return self;
}
于 2013-03-12T11:51:30.703 回答
0

用init替换您的 BSViewController viewDidLoad方法,如下所示:

- (id)init {

if (self = [super init]) {

    NSArray*  _array = [NSArray arrayWithObjects: @"manny",@"moe",nil];
    self.array = _array;
    view.number = 25;

}
return self;
}
于 2013-03-12T12:22:30.753 回答