iphone - 类之间传递数据的差异

标签 iphone ios xcode

代码的第 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;来自 implementationClassB , textLabelClassB 的 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.dataToDisplayviewDidLoad ,它就像一个冠军(就像它为你做的那样)。但是 UILabel IBOutletviewDidLoad 之前,属性(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/

相关文章:

iphone - 为什么我的网站在我的 iPhone Safari 浏览器上看起来不一样,是我做错了什么吗?

iphone - applicationWillEnterForeground 从未调用过

ios - Xcode 11 Beta 和 Carthage Bootstrap

ios - 如何使用 Xcode 中的 block 进行有效调试

ios - 当我尝试选择路由 : pedestrians in Capabilities > Maps 时 Xcode 崩溃

iphone - 如何在 iPhone-OS 中链接动画?

iphone - 如何在全屏 OpenGL ES 应用程序上显示 iPhone/iPad 键盘

ios - IBOutlet 引用两个 Storyboard

ios - NaN 会导致这个核心音频 iOS 应用程序偶尔崩溃吗?

ios - TabBar 应用程序 - 在显示 View 之前加载数据