You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
weibo/Weibo/UserData.swift

64 lines
2.0 KiB

//
// UserData.swift
// Weibo
//
// Created by Qihua Pan on 2020/8/18.
// Copyright © 2020 Qihua Pan. All rights reserved.
//
import Foundation
import CoreData
class UserData{
static func getUser()->User{
let fetchRequest: NSFetchRequest = User.fetchRequest()
let context=getContext()
do {
let result = try context.fetch(fetchRequest)
print("count=\(result.count)")
if result.count>0{
return result[0]
}else{
let user=NSEntityDescription.insertNewObject(forEntityName: "User", into: context) as! User
saveContext()
return user
}
} catch {
fatalError();
}
}
static func clearAll(){
let context=getContext()
let fetchRequest: NSFetchRequest = User.fetchRequest()
do {
let result = try context.fetch(fetchRequest)
for item in result{
context.delete(item)
}
saveContext()
} catch {
fatalError();
}
}
static func saveContext () {
let context=getContext()
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() 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
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
static func getContext()->NSManagedObjectContext{
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
print("context=\(context)")
return context
}
}