Singleton managedObjectContext

与世无争的帅哥 提交于 2019-12-19 04:05:39

问题


I want to use the singleton UIApplication to access the managedObjectContext of the AppDelegate. But when I write

[[[UIApplication sharedApplication] delegate] managedObjectContext]

or

[[[UIApplication sharedApplication] delegate] __managedObjectContext]

it doesn't work.

But this line works fine :

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

Do you have a solution ? Niels


回答1:


Try casting it to your actual app delegate implementation, like

 [(MyAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];

And to add

#import "MyAppDelegate.h"

at the top of the file.




回答2:


Using a singleton like this is bad practice, and even explicitly discouraged in the Core Data documentation:

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.

Dependency injection (i.e. giving the view controller what it needs) is better in almost all situations. It really isn't good to see [[UIApplication sharedApplication] delegate] all over an application's code because it makes the code hard to reuse, hard to write tests for, etc.



来源:https://stackoverflow.com/questions/6622699/singleton-managedobjectcontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!