Swiftで遊ぼう! on Hatena

あしたさぬきblogでやってた初心者オヤジのiOSプログラミング奮闘記がHatenaに来ました

Swiftで遊ぼう! - 633 - Zoomania 3

DataHelperクラスを作ったのでこれを実際AppDelegateで呼びます。以下のメソッドに書き込みます。

func application(application: UIApplication, 
 didFinishLaunchingWithOptions launchOptions: 
                    [NSObject: AnyObject]?) -> Bool {
  // Override point for customization after application launch.
        
  let dataHelper = 
                DataHelper(context: self.managedObjectContext)
        
  dataHelper.seedDataStore()
        
  dataHelper.printAllZoos()
  dataHelper.printAllClassifications()
  dataHelper.printAllAnimals()
        
  return true
}

毎回データーベースをクリーンにしたいので次のメソッドをNSPersistentStorCoordinatorに加えます。NSPersistentStoreCoordinatorクラスが直接SQliteとデータをやり取りするクラスなので、これが呼ばれた時に必ず残っているデータを消去するステップです。これは開発中にアプリを立ち上げる度にクリアされてクリーンスタートできるので開発しやすいということです。

lazy var persistentStoreCoordinator: 
   NSPersistentStoreCoordinator = {
   // The persistent store coordinator for the application. 
  // This implementation creates and returns a coordinator, 
   // having added the store for the application to it. 
   // This property is optional since there are legitimate error 
   // conditions that could cause the creation of the store to fail.
   // Create the coordinator and store
  let coordinator = NSPersistentStoreCoordinator(managedObjectModel: 
                       self.managedObjectModel)
        
  let url = self.applicationDocumentsDirectory
                      .URLByAppendingPathComponent("Zoomania.sqlite")
        
  do {
       try NSFileManager.defaultManager().removeItemAtURL(url)
   // これでSQLiteのデータベースからデータを消去します。
     } catch let error as NSError {
       print("error is \(error)")
     }

これで準備完了です。

今日はこれだけ。