receive ivar in other class [closed]

微笑、不失礼 提交于 2019-12-12 03:50:56

问题


I have two view controllers: BSViewController which contains the source ivars number and array, and BSotherViewController which as the target needs to receive the ivars . (BSViewController has a button on it that is segues to BSotherViewController.)

How can I access the value of the two ivars in 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

The problem below is that aview.number is 0, not 25; and aview.array is null.

#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

回答1:


When you instantiate the BSViewController from BSOtherViewController you are calling the init method. The values is set in viewDidLoad in BSViewController, and that method won't be invoked until the view is actually loaded.

Try to override the init method and set the values

- (id)init {

if (self = [super init]) {
    //Set values
     NSArray*  _array = [NSArray arrayWithObjects: @"manny",@"moe",nil];
     self.array = _array;
     self.number = 25;
}
return self;
}



回答2:


Replace your BSViewController viewDidLoad method with init like this :

- (id)init {

if (self = [super init]) {

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

}
return self;
}


来源:https://stackoverflow.com/questions/15360290/receive-ivar-in-other-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!