从另一个视图控制器获取属性

时间:2016-04-25 15:51:59

标签: ios objective-c properties viewcontroller

当我在视图控制器B中时,我想从Viewcontroller A访问NSString

在VIEWCONTROLLER A .H

@property (nonatomic,strong) NSString *test;

在视图控制器中.M

@synthesize test;

// view did load

test = @"dikke bertha"; 

在VIEWCONTROLLER B .H

#import "ViewcontrollerA.h"

@property (weak, nonatomic ) ViewcontrollerA *VCA

在视图控制器B .M

synthesize VCA;

NSLog (@"%@", VCA.test )

NSLOG TURN NULL ...

1 个答案:

答案 0 :(得分:0)

为了使你的字符串出现在Class 2中,因为你已经在另一个类(Class 1)中声明它,你需要这样做,以便初始化Class 1对象也为你的字符串赋值。例如。

ViewControllerA.h:

@interface ViewControllerA : UIViewController
@property (weak, nonatomic) NSString *test;
-(instancetype)init;
@end

ViewControllerA.m

#import "ViewControllerA.h"

@interface ViewControllerA ()
@end

@implementation ViewControllerString

-(instancetype)init{
    self = [super init];
    if (self) {
      _test = @"Testing stuff";
    }
    return self;
}

ViewControllerB.h:

#import "ViewControllerA.h"
@interface ViewControllerB : UIViewController
@property (strong, nonatomic) ViewControllerA *vcString;
@end

ViewControllerB.m:

#import "ViewControllerB.h"

@interface ViewControllerB ()
@end

@implementation ViewControllerB

- (void)viewDidLoad {
    [super viewDidLoad];

    _vcString = [[ViewControllerA alloc]init];
    NSLog(@"%@", self.vcString.test);
}

在ViewControllerA中创建特定的初始化程序时,无论何时执行此操作都会使其成为:

ViewControllerA *viewControllerAObject = [ViewControllerA alloc]init]; 

在另一个类中,在初始化时创建一个带有特定文本字符串的ViewControllerA对象。