代码的第 1 部分工作正常。第 2 部分显示了代码中的微小更改,这些更改会导致代码按预期停止工作(没有错误/警告)。
第 1 部分:(作品)
#import "ClassA.h"
#import "ClassB.h"
@implementation ClassA
- (void) sendData
{
NSString *temp = [NSString stringWithFormat:@"HI!"];
ClassB *classBObject = [[ClassB alloc] init];
classBObject.dataToDisplay = temp;
self.view = classBObject.view;
}
@end
B类接口(interface):
#import <UIKit/UIKit.h>
@interface ClassB : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *textLabel;
@property NSString * dataToDisplay;
@end
B类的实现:
#import "ClassB.h"
@implementation ClassB
@synthesize dataToDisplay, textLabel;
- (void)viewDidLoad
{
[super viewDidLoad];
textLabel.text = dataToDisplay;
}
@end
第2部分:
但如果我改变
- (void)sendData
A类到以下:- (void) sendData
{
NSString *temp = [NSString stringWithFormat:@"HI!"];
ClassB *classBObject = [[ClassB alloc] init];
classBObject.textLabel.text = temp; // statement changed from Part 1.
self.view = classBObject.view;
}
并删除
textLabel.text = dataToDisplay;
来自 implementation
的 ClassB
, textLabel
在 ClassB
的 View Controller 上没有得到更新。你能建议一下吗,为什么会这样?谢谢!
编辑1:
声明中:
classBObject.textLabel.text = temp; // statement changed from Part 1.
,我错过了.text
复制粘贴时。请原谅我。
最佳答案
第二种技术不正确的原因(除了 .text
末尾缺少的 textLabel
)是当您从 B 类初始化程序返回时,底层的 UILabel
对应 textLabel
无疑还没有被创造出来。如果你看这个diagram您会看到 View 配置并未在初始化方法结束时完成,而是在访问时完成。因此,您必须推迟对用户界面控件的任何访问,直到 viewDidLoad
.
更新:
当我运行以下代码时,我在日志中得到“0x0”,证明 UILabel
在我的第二个 View 中仍然是 nil
并且还没有初始化,正如我所预料的那样。当viewDidLoad
在我的第二个 Controller 中设置 self.textLabel.text = self.dataToDisplay
在 viewDidLoad
,它就像一个冠军(就像它为你做的那样)。但是 UILabel
IBOutlet
在 viewDidLoad
之前,属性(property)是不可靠的.
SecondViewController *controller = [[SecondViewController alloc] init];
NSLog(@"%p", controller.textLabel);
controller.dataToDisplay = @"from first view";
[self presentViewController:controller animated:YES completion:nil];
关于iphone - 类之间传递数据的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12762846/