在其他班级接受ivar

时间:2013-03-12 11:45:54

标签: objective-c ivar

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

如何在BSotherViewController中访问两个ivars的值?

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

2 个答案:

答案 0 :(得分:1)

BSViewController实例化BSOtherViewController时,您正在调用init方法。这些值在viewDidLoad中的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;
}

答案 1 :(得分: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;
}