9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

iOS9 CoreData NSManagedObjectContext()の初期化方法の変更について

Last updated at Posted at 2015-11-07

'init()' was deprecated in iOS 9.0: Use -initWithConcurrencyType: instead

NSManagedObjectContext
Managing Concurrency

sample.swift
// iOS8
var managedObjectContext = NSManagedObjectContext()

// iOS9
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)

設定できるconcurrencyTypeは、

  • ConfinementConcurrencyType
  • デフォルトだけど、オススメされていない。(下位互換)
  • MainQueueか、PrivateQueueを選択しろと……。
  • MainQueueConcurrencyType
  • メインスレッドで実行
  • PrivateQueueConcurrencyType
  • 専用のスレッドで実行

私が利用しているパターンは、
AppDelegateでコンテキストを生成して、それをDAO?的なマネージャを通してViewController()から利用するといったものなので、『MainQueueConcurrencyType』を選択しました。
ViewController()内で完結する場合や、バックグラウンドでの実行の場合には、『PrivateQueueConcurrencyType』の方がよいかもしれません。

AppDelegate.swift
class AppDelegate: UIResponder, UIApplicationDelegate {

	~~~

    // MARK: - Core Data stack
    lazy var applicationDocumentsDirectory: NSURL = {
        let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
        return urls[urls.count-1] 
        }()
    
    lazy var managedObjectModel: NSManagedObjectModel = {
        let modelURL = NSBundle.mainBundle().URLForResource("Hoge", withExtension: "momd")!
        return NSManagedObjectModel(contentsOfURL: modelURL)!
        }()
    
    lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
        var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
        let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("*****.sqlite")
        var error: NSError? = nil
        var failureReason = "There was an error creating or loading the application's saved data."
        do {
            try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
        } catch var error1 as NSError {
            error = error1
            coordinator = nil

            var dict = [String: AnyObject]()
            dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
            dict[NSLocalizedFailureReasonErrorKey] = failureReason
            dict[NSUnderlyingErrorKey] = error
            error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)

            NSLog("Unresolved error \(error), \(error!.userInfo)")
            abort()
        } catch {
            fatalError()
        }
        
        return coordinator
        }()
    
    lazy var managedObjectContext: NSManagedObjectContext? = {
        let coordinator = self.persistentStoreCoordinator
        if coordinator == nil {
            return nil
        }
        // ココ
        var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
        managedObjectContext.persistentStoreCoordinator = coordinator
        return managedObjectContext
        }()
    
    // MARK: - Core Data Saving support
    func saveContext () {
        if let moc = self.managedObjectContext {
            var error: NSError? = nil
            if moc.hasChanges {
                do {
                    try moc.save()
                } catch let error1 as NSError {
                    error = error1
                    NSLog("Unresolved error \(error), \(error!.userInfo)")
                    abort()
                }
            }
        }
    }
}
HogeStoreManager.swift
class HogeStoreManager {
    let appDelegate:AppDelegate!
    let context:NSManagedObjectContext!
    let entity: NSEntityDescription!
    let entityName:String = "HogeStore"
    
    init() {
        appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        context     = appDelegate.managedObjectContext!
        entity      = NSEntityDescription.entityForName(entityName, inManagedObjectContext: context)
    }
    
    func add(title:String, body:String, noteId:NSNumber) {
        let param = PageStore(entity: entity, insertIntoManagedObjectContext: context)
        param.title         = title
        param.body          = body
        param.note_id       = noteId
        param.submit_date   = NSDate()
        param.update_date   = NSDate()
        param.seq           = NSNumber(integer: 0)
        appDelegate.saveContext()
    }

	~~~
}

元々、このパターンを選択した理由は、内部のSQLiteストレージから、iCloudへの移行が楽そうだったからなのですが、数ヶ月経っても進まず。
コードは書いてあるけど、いまいちユビキティコンテナを信用しきれない。
コンテナに放り込んでやれば、iCloudがよろしくやってくれて、同期されるんだけどね。

9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?