gpt4 book ai didi

iphone - 访问其他类中的变量时为空值(组合导航和选项卡 Controller )

转载 作者:行者123 更新时间:2023-11-29 04:46:29 25 4
gpt4 key购买 nike

我有一个位于选项卡栏 Controller 内的导航 Controller ,每当我尝试从导航 Controller 内的类访问类时,我的所有值都会返回(null)。

这就是我正在尝试做的事情。

AppDelegate.h

@interface AppDelegate : UIResponder <UIApplicationDelegate, UITabBarControllerDelegate> {
NSString *searchQueryA;
}

@property (strong, nonatomic) NSString *searchQueryA;

ThirdViewController.h

#import "MasterViewController.h"
#import "AppDelegate.h"

@class MasterViewController;

@interface ThirdViewController : UIViewController {
code
}

@property (strong, retain) MasterViewController *masterViewController;

ThirdViewController.m

- (IBAction)showDetail:(id)sender {
AppDelegate *appDelegate = [[AppDelegate alloc] init];
appDelegate.searchQueryA = _searchField.text;
masterViewController = [[MasterViewController alloc] initWithNibName:@"MasterViewController" bundle:nil];
[self.navigationController pushViewController:masterViewController animated:YES];
}

MasterViewController.h

#import "AppDelegate.h"
@interface MasterViewController : UITableViewController
{
NSString *searchQueryM;
}

@property (nonatomic, strong) NSString *searchQueryM;

MasterViewController.m

 AppDelegate *appDelegate = [[AppDelegate alloc] init];
searchQueryM = appDelegate.searchQueryA;

NSLog(@"%@", searchQueryM);

在日志中我可以看到 searchQueryM 为(null)。如果我尝试从另一个类访问 AppDelegate 中的变量(不涉及导航 Controller ),那么它显示得非常好。我错过了什么?

如果您需要查看更多代码,我很乐意提供。

编辑:

为了便于阅读,我将在此处发布代码更改:

我的 AppDelegate.h 中有委托(delegate)

正如 Leonardo 指出的那样,我只分配并初始化了我的 AppDelegate。我将该片段更改为:

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
searchQueryM = appDelegate.searchQueryA;

但仍然没有进行,因为 searchQueryM 仍然是(空)。

这就是我使用 searchQueryM 所做的事情

MasterViewController.h

@interface MasterViewController : UITableViewController
{
NSString *searchQueryM;
}

@property (nonatomic, strong) NSString *searchQueryM;

MasterViewController.m

@synthesize searchQueryM;

我对 Objective-C(以及面向对象编程)相当陌生,可能应该读一本关于它的书,但在我看来,没有比这更多的东西了。如果我错了请纠正我。

编辑2

ThirdViewController.h

@interface ThirdViewController : UIViewController {
UITextField *_searchField;
}

@property (nonatomic, strong) IBOutlet UITextField *searchField;

ThirdViewController.m

 @synthesize searchField = _searchField;

...

- (IBAction)showDetail:(id)sender {
_code_
NSLog(@"%@", searchField.text);
_code_

如果我在 searchField 文本字段中输入“asd”并将其与日志一起输出,我会得到“asd”。 }

最佳答案

为什么要分配 init 你的 AppDelegate ?应通过以下方式访问 AppDelegate:

[[UIApplication sharedApplication] delegate]

我们应该看看你通常如何初始化searchQueryM,你得到的是null,可能是因为AppDelegate只被分配和初始化,但初始化其属性的逻辑永远不会被调用。

关于iphone - 访问其他类中的变量时为空值(组合导航和选项卡 Controller ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9573101/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com