gpt4 book ai didi

ios - Objective C View Controller 属性不保存

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:59:26 26 4
gpt4 key购买 nike

您好,我正在尝试设置我的UIViewController 的 托管对象上下文,但对象上下文未保存。这是代码:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
my_TableViewController *viewController = [mainStoryboard instantiateViewControllerWithIdentifier:@"coretut"];
if ([viewController isKindOfClass:[my_TableViewController class]]) {
[viewController setOManagedObjectContext:self.managedObjectContext];
}
NSLog(@"%@", self.managedObjectContext);
NSLog(@"%@", viewController.oManagedObjectContext);
}

下面的输出是

Apple_Tutorial[11241:461826] <NSManagedObjectContext: 0x7fb558d86600>
Apple_Tutorial[11241:461826] <NSManagedObjectContext: 0x7fb558d86600>

但是当我调用

NSLog(@"%@", self.oManagedObjectContext);

viewDidLoad() 中,my_TableViewController 的输出为 null。 oManagedObjectContext 声明为 (strong, nonatomic)。有谁知道为什么 oManagedObjectContext 变为空?

viewDidLoad代码:

- (void)viewDidLoad {
[super viewDidLoad];
UINib *nib = [UINib nibWithNibName:@"my_TableViewCell" bundle:nil];
[[self tableView] registerNib:nib forCellReuseIdentifier:@"tableViewCell"];

NSLog(@"%@", self.oManagedObjectContext);
}

最佳答案

问题是 didFinishLaunchingWithOptions 正在实例化一个新的 View Controller ,然后什么都不做(即丢弃它)。所以您正在查看两个不同的 View Controller 实例。


您可以让应用委托(delegate)设置 Root View Controller 的 oManagedObjectContext:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
ViewController *controller = (id)self.window.rootViewController;
NSAssert([controller isKindOfClass:[ViewController class]], @"Root controller should be `ViewController`, but is %@", controller);

controller.oManagedObjectContext = self.managedObjectContext;

return YES;
}

显然,如果您的 View Controller 不是根 Controller (例如,如果它在某些容器 View Controller 中,例如导航 Controller 、标签栏 Controller 、自定义容器 Controller 等),那么您必须调整上面的代码在该层次结构中导航以找到您的 View Controller 类。

关于ios - Objective C View Controller 属性不保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31065866/

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