核心数据 - 无需先插入即可获取

时间:2016-11-30 11:41:56

标签: ios swift core-data swift3

我已将数据模型和核心数据添加到现有项目中,我可以成功编写对象并保存/插入,但我不能只在数据库中获取最新信息。我究竟做错了什么?或者我误解了Core Data的工作原理?

我可以插入一个对象,然后使用下面的代码获得所需的结果 - 但是我无法在不使用插入的情况下检索对象。我想存储一个"令牌"所以app会记住它。

let dc = DataController()
let moc = dc.managedObjectContext

let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Token")
//fetchRequest.returnsObjectsAsFaults = false

do {
    let entities = try moc.fetch(fetchRequest) as! [NSManagedObject]
    print(entities.count) // prints 0
    print(entities) // prints []
    for entity in entities {
        print(entities.count) // these dont work because of 0 results
        print(entity) // these dont work because of 0 results
    }
} catch {
    print("could not fetch")
}

调试日志:

0
[]
CoreData: annotation: Connecting to sqlite database file at "/Users/xxxx/Library/Developer/CoreSimulator/Devices/1231231-123123-123123-123123-123123123/data/Containers/Data/Application/123123-123123-123123-123123-123123123/Documents/DataModel.sqlite"
CoreData: sql: SELECT TBL_NAME FROM SQLITE_MASTER WHERE TBL_NAME = 'Z_METADATA'
CoreData: sql: pragma recursive_triggers=1
CoreData: sql: pragma journal_mode=wal
CoreData: sql: SELECT Z_VERSION, Z_UUID, Z_PLIST FROM Z_METADATA
CoreData: sql: SELECT TBL_NAME FROM SQLITE_MASTER WHERE TBL_NAME = 'Z_MODELCACHE'
CoreData: annotation: Disconnecting from sqlite database.

我已经打开了sqlite文件和我之前插入的对象。

2 个答案:

答案 0 :(得分:1)

您可以这样做以检索数据。

func retriveSaveData(){

    let request:NSFetchRequest<TestData> = TestData.fetchRequest()
    do {
        let data = try managedObjectcontext.fetch(request) as [TestData]

        if let str = data.first?.name{
            // Your retrieve data
            print(str)
        }
    }catch{
        let error  = error as NSError
        print("\(error)")
    }
}

用于保存和更新数据。

 func saveToDataBase(data:[TestData]){
        for data1 in data{

            let request:NSFetchRequest<TestData> = TestData.fetchRequest()
            do {
                let count = try managedObjectcontext.count(for: request)
                if count == 0 {
                    // save data according to your requirement.
                    print(data1)
                }else{

                    //if anything you want to update then wright here
                }

            }catch{
                let error  = error as NSError
                print("\(error)")
            }
        }
    }

希望它能帮到你

答案 1 :(得分:0)

由于您知道要在持久性存储中搜索的实体,因此请确保NSFetchRequest(现在是Swift 3中的通用)是Token对象:

let fetchRequest = NSFetchRequest<Token>(entityName: "Token")

您也可以将其作为令牌项目投射:

let entities = try moc.fetch(fetchRequest) as! Token