我有两个视图控制器:BSViewController
,其中包含源ivars number
和array
,以及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
答案 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;
}