Core Data singleton manager?

前端 未结 3 717
我在风中等你
我在风中等你 2021-02-01 06:39

What technical reasons are there not to make a singleton class to manage my Core Data? I\'m trying to make a decision now, if I should strip out all of the boilerplate core data

3条回答
  •  执笔经年
    2021-02-01 07:11

    There are two important considerations (note these are not the only two) when deciding if a singleton is right for you:

    1. Threading
    2. Memory Usage

    Threading

    Singletons are convenient, but if your application uses multiple threads you might be tempted to write something like this:

    [[CDSingleton managedObjectContext] executeFetchRequest:someFetch];
    //later on a background thread you might write
    NSManagedObject *object = [[CDSingleton managedObjectContext] objectWithID:objectID];
    

    Shortly after that, your application will crash because you've accessed a managedObjectContext which was likely created on the main thread from some other thread.

    Memory Usage

    Singletons never go away, that's the point of a Singleton. Thus, they also never willingly free their consumed resources. In the case of CoreData that means the managed object context will continue to hold managed objects in memory until you call -reset or -save:.

    That could be bad if your app uses a lot of data.

提交回复
热议问题