您好,登錄后才能下訂單哦!
在Cocoa Touch應用中配置和使用Core Data需要按照以下步驟進行:
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應用中配置和使用Core Data的基本步驟。通過遵循這些步驟,您就可以在您的應用程序中使用Core Data來管理數據。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。