2016-06-30 13 views
11

Ich entwickle eine App in einem neuen Xcode 8 und ich bemerkte eine offensichtliche Sache. Xcode hat mich Core-Daten mit den neuesten API-Referenzen generiert. Wenn ich also das Implementierungsziel auf iOS 8 oder 9 ändere, konfligiert es und schlägt mir vor, in Klammern zu gehen: AVAILABLE meinen Core Data Code. Das bedeutet, ich muss Core Data Code von der vorherigen API neu schreiben. Hat jemand Vorlage für AppDelegate mit beiden oder vielleicht ist es möglich, Xcode generieren sie? Vielen Dank im Voraus!Xcode 8 Core Data Template für iOS 8,9

+1

Ich glaube nicht, dass dies derzeit in Xcode 8 möglich ist. Aber es ist nicht schwer, eigenen Code zu schreiben, um den Core Data Stack zu erstellen - es gibt nichts Magisches daran, es ist nur Code. Andernfalls erstellen Sie ein Projekt mit Xcode 7.3.1 (noch verfügbar) und melden Sie einen Fehler. –

Antwort

47

Da sollte niemand Xcode 7 zum Herunterladen haben, installieren Sie es, ein neues Projekt starten, und den Port der Template-Code zu schnellen 3 nur Kerndaten zu verwenden, während immer noch iOS 8 & 9 unterstützt:

Swift 2 Kern Datenvorlage Methoden aus AppDelegate.swift:

lazy var applicationDocumentsDirectory: NSURL = { 
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.cadiridris.coreDataTemplate" in the application's documents Application Support directory. 
    let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) 
    return urls[urls.count-1] 
}() 

lazy var managedObjectModel: NSManagedObjectModel = { 
    // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. 
    let modelURL = NSBundle.mainBundle().URLForResource("coreDataTemplate", withExtension: "momd")! 
    return NSManagedObjectModel(contentsOfURL: modelURL)! 
}() 

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("SingleViewCoreData.sqlite") 
    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 { 
     // Report any error we got. 
     var dict = [String: AnyObject]() 
     dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" 
     dict[NSLocalizedFailureReasonErrorKey] = failureReason 

     dict[NSUnderlyingErrorKey] = error as NSError 
     let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) 
     // Replace this with code to handle the error appropriately. 
     // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
     NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") 
     abort() 
    } 

    return coordinator 
}() 

lazy var managedObjectContext: NSManagedObjectContext = { 
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. 
    let coordinator = self.persistentStoreCoordinator 
    var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) 
    managedObjectContext.persistentStoreCoordinator = coordinator 
    return managedObjectContext 
}() 

// MARK: - Core Data Saving support 

func saveContext() { 
    if managedObjectContext.hasChanges { 
     do { 
      try managedObjectContext.save() 
     } catch { 
      // Replace this implementation with code to handle the error appropriately. 
      // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
      let nserror = error as NSError 
      NSLog("Unresolved error \(nserror), \(nserror.userInfo)") 
      abort() 
     } 
    } 
} 

Umgerechnet auf schnelle 3:

lazy var applicationDocumentsDirectory: URL = { 
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.cadiridris.coreDataTemplate" in the application's documents Application Support directory. 
    let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) 
    return urls[urls.count-1] 
}() 

lazy var managedObjectModel: NSManagedObjectModel = { 
    // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. 
    let modelURL = Bundle.main.url(forResource: "coreDataTemplate", withExtension: "momd")! 
    return NSManagedObjectModel(contentsOf: modelURL)! 
}() 

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.appendingPathComponent("SingleViewCoreData.sqlite") 
    var failureReason = "There was an error creating or loading the application's saved data." 
    do { 
     try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil) 
    } catch { 
     // Report any error we got. 
     var dict = [String: AnyObject]() 
     dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject? 
     dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject? 

     dict[NSUnderlyingErrorKey] = error as NSError 
     let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) 
     // Replace this with code to handle the error appropriately. 
     // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
     NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") 
     abort() 
    } 

    return coordinator 
}() 

lazy var managedObjectContext: NSManagedObjectContext = { 
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. 
    let coordinator = self.persistentStoreCoordinator 
    var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) 
    managedObjectContext.persistentStoreCoordinator = coordinator 
    return managedObjectContext 
}() 

// MARK: - Core Data Saving support 

func saveContext() { 
    if managedObjectContext.hasChanges { 
     do { 
      try managedObjectContext.save() 
     } catch { 
      // Replace this implementation with code to handle the error appropriately. 
      // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
      let nserror = error as NSError 
      NSLog("Unresolved error \(nserror), \(nserror.userInfo)") 
      abort() 
     } 
    } 
} 
+0

Hey, wenn ich mein Projekt in xcode 8 gemacht habe, ist die Dateiendung für das Datenmodell "xcdatamodeld". Muss ich das im Code ändern? oder würde momd arbeiten? Danke – Munib

+3

Wie im folgenden Link weiter beschrieben: "Die Mom und Momd Dateien sind kompilierte Versionen von xcdatamodel und xcdatamodeld Dateien." http://stackoverflow.com/a/10580677/3034715 Sie möchten es auf die kompilierte Version, d. H. Die Mutter/Mutter-Erweiterung. – DCToDaylight

10

Dank DCToDaylight's answer. Ich habe diese Datei erstellt, die Sie einfach per Drag and Drop ziehen können. Ich habe auch meinen verwalteten Objekt-Kontext statisch und meine Init-Methode privat gemacht. Damit jemand nicht versehentlich einen neuen Kontext instanziieren kann.

Die Funktion getContext macht es jedes Mal einfacher, wenn Sie etwas mit Kerndaten machen.

Die Idee, einen statischen managedObjectContext, eine separate Datei und die Funktion zu erstellen, kam von this YouTube tutorial.

Für dieses Beispiel habe ich eine neue Datei mit dem Namen DatabaseController.swift erstellt und diesen ganzen Code dort eingegeben. Dadurch wird mein Code einfacher zu verwalten und zu lesen. Sie können auch von der // MARK: - Core Data stack zum Ende der Datei kopieren und den ähnlichen Code in Ihnen AppDelegate.swift ersetzen und es wird funktionieren.

import Foundation 
import CoreData 

class DatabaseController { 

    private init() { 

    } 

    class func getContext() -> NSManagedObjectContext { 
     return DatabaseController.managedObjectContext 
    } 
    // MARK: - Core Data stack 

    static var managedObjectContext: NSManagedObjectContext = { 

     var applicationDocumentsDirectory: URL = { 
      // The directory the application uses to store the Core Data store file. This code uses a directory named "com.cadiridris.coreDataTemplate" in the application's documents Application Support directory. 
      let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) 
      return urls[urls.count-1] 
     }() 

     var managedObjectModel: NSManagedObjectModel = { 
      // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. 
      let modelURL = Bundle.main.url(forResource: "YOUR_APP_NAME", withExtension: "momd")! 
      return NSManagedObjectModel(contentsOf: modelURL)! 
     }() 

     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: managedObjectModel) 
      let url = applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite") 
      var failureReason = "There was an error creating or loading the application's saved data." 
      do { 
       try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil) 
      } catch { 
       // Report any error we got. 
       var dict = [String: AnyObject]() 
       dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject? 
       dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject? 

       dict[NSUnderlyingErrorKey] = error as NSError 
       let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) 
       // Replace this with code to handle the error appropriately. 
       // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
       NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") 
       abort() 
      } 

      return coordinator 
     }() 

     // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. 
     let coordinator = persistentStoreCoordinator 
     var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) 
     managedObjectContext.persistentStoreCoordinator = coordinator 
     return managedObjectContext 
    }() 

    // MARK: - Core Data Saving support 

    class func saveContext() { 
     if managedObjectContext.hasChanges { 
      do { 
       try managedObjectContext.save() 
      } catch { 
       // Replace this implementation with code to handle the error appropriately. 
       // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
       let nserror = error as NSError 
       NSLog("Unresolved error \(nserror), \(nserror.userInfo)") 
       abort() 
      } 
     } 
    } 
} 

Davon abgesehen, aus offensichtlichen Gründen können Sie nicht den NSPersistantContainer verwenden, so dass Sie das Core Data Stack-Verfahren unter Verwendung des managedObjectContext verwenden.

0

Wenn Sie eine schnelle Lösung für das wollen, müssen Sie nur eine objektive c-Klasse hinzufügen enthält allgemeine Funktion core-Daten, um Referenz von NSManagedObjectContext und NSPersistentStoreCoordinator zu bekommen. (Sie können Code auf SO oder anderen Website finden, kontaktieren Sie mich, falls Sie diese Klasse benötigen.)

Nach dem Hinzufügen der Klasse @Available 10-Klausel verwenden und in anderen Teil Code hinzufügen, um Referenz für das oben genannte Modell zu nehmen.

Lassen Sie mich wissen, wenn jemand etwas falsch gefunden hat.

Verwandte Themen