您好,登錄后才能下訂單哦!
在Cocoa Touch應(yīng)用中配置和使用Core Data需要按照以下步驟進(jìn)行:
import CoreData
class AppDelegate: UIResponder, UIApplicationDelegate {
var persistentContainer: NSPersistentContainer!
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
persistentContainer = NSPersistentContainer(name: "YourDataModelName")
persistentContainer.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error {
fatalError("Failed to load persistent stores: \(error)")
}
})
return true
}
}
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "EntityName", in: context)
let newObject = NSManagedObject(entity: entity!, insertInto: context)
newObject.setValue("Value", forKey: "AttributeName")
do {
try context.save()
} catch {
print("Failed to save context: \(error)")
}
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "EntityName")
do {
let results = try context.fetch(fetchRequest)
for result in results as! [NSManagedObject] {
let value = result.value(forKey: "AttributeName") as! String
print(value)
}
} catch {
print("Failed to fetch data: \(error)")
}
以上是在Cocoa Touch應(yīng)用中配置和使用Core Data的基本步驟。通過遵循這些步驟,您就可以在您的應(yīng)用程序中使用Core Data來管理數(shù)據(jù)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。