gpt4 book ai didi

iphone - 单例 managedObjectContext

转载 作者:可可西里 更新时间:2023-11-01 06:18:19 27 4
gpt4 key购买 nike

我想使用单例 UIApplication 来访问 AppDelegate 的 managedObjectContext。但是当我写

[[[UIApplication sharedApplication] delegate] managedObjectContext]

[[[UIApplication sharedApplication] delegate] __managedObjectContext]

它不起作用。

但是这条线工作正常:

NSLog(@"Seeking for the AppDelegate : %@", [[[UIApplication sharedApplication] delegate] class]);

你有解决办法吗?尼尔斯

最佳答案

像这样使用单例是不好的做法,甚至在 Core Data 文档中明确反对:

http://developer.apple.com/library/ios/#documentation/DataManagement/Conceptual/CoreDataSnippets/Articles/stack.html

A view controller typically shouldn’t retrieve the context from a global object such as the application delegate. This tends to make the application architecture rigid. Neither should a view controller typically create a context for its own use. This may mean that operations performed using the controller’s context aren’t registered with other contexts, so different view controllers will have different perspectives on the data.

When you create a view controller, you pass it a context. You pass an existing context, or (in a situation where you want the new controller to manage a discrete set of edits) a new context that you create for it. It’s typically the responsibility of the application delegate to create a context to pass to the first view controller that’s displayed.

依赖注入(inject)(即 View Controller 它需要的东西)几乎在所有情况下都更好。在整个应用程序代码中看到 [[UIApplication sharedApplication] delegate] 确实不好,因为它使代码难以重用,难以为其编写测试等。

关于iphone - 单例 managedObjectContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6622699/

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