swift:检查核心数据中的记录

时间:2016-03-23 04:17:14

标签: ios swift core-data

有没有办法从Xcode检查核心数据?

我创建了两个函数(写入DB,从DB读取),这些函数没有失败,但是当它应该返回写入数据时,read返回空数组。

功能:

func writeData () {
        appDel = UIApplication.sharedApplication().delegate as! AppDelegate
    context = appDel.managedObjectContext

        let newRecord = NSEntityDescription.insertNewObjectForEntityForName("CountryList", inManagedObjectContext: context) as NSManagedObject

        let timestamp = NSDate()

        for geo in geoArray {

        //geoArray - array of dictionaries ([CountryName: "Lithuania", TelCode: 370],[CountryName: "Belarus", TelCode: 375],[CountryName: "Latvia", TelCode: 371])             
        //geo - Dictionary of tipe <String: AnyObject>
        // CoreData: countryName type is String

        newRecord.setValue(timestamp, forKey: "dateUploaded")
        newRecord.setValue(String(geo["CountryName"]!), forKey: "countryName")

            do {
                try context.save()
                print("Saved successfully")
            } catch _ {
                print("there was issue saving data!")
            }  

          }


        } 







  func loadData(country: String) {
        appDel = UIApplication.sharedApplication().delegate as! AppDelegate
        context = appDel.managedObjectContext


        results = [AnyObject]()

        let request = NSFetchRequest(entityName: "CountryList")
        request.resultType = NSFetchRequestResultType.DictionaryResultType

        request.predicate = NSPredicate(format: "countryName = %@", country)



        let sort1 = NSSortDescriptor(key: "dateUploaded", ascending: true)

        request.sortDescriptors = [sort1]

        do {
            results = try context.executeFetchRequest(request)
            print(results!)

        } catch _ {
            print ("error trying to fetch!")
        }
    }

我想从Xcode查看我的CoreData实体中是否有任何记录。那可能吗?

感谢

1 个答案:

答案 0 :(得分:0)

您实际上是在循环中更改相同的核心数据对象。因此,最终在循环结束时,您将只剩下一个具有数组中最后一个国家/地区名称的对象。你应该每次在循环中创建一个newRecord

在for循环中移动此行,它应该可以正常工作。

let newRecord = NSEntityDescription.insertNewObjectForEntityForName("CountryList", inManagedObjectContext: context) as NSManagedObject

请注意,您正在创建核心数据管理对象并在循环内更改它并保存多次保存同一对象。如果要保存多个对象,则必须每次都创建一个新对象,设置其值然后保存。您还可以将保存部分移出循环。

func writeData () {
    let appDel = UIApplication.sharedApplication().delegate as! AppDelegate
    let context = appDel.managedObjectContext
    let timestamp = NSDate()
    for geo in geoArray {
        let newRecord = NSEntityDescription.insertNewObjectForEntityForName("CountryList", inManagedObjectContext: context) as NSManagedObject
        newRecord.setValue(timestamp, forKey: "dateUploaded")
        newRecord.setValue(String(geo["CountryName"]!), forKey: "countryName")
    }
    do {
        try context.save()
        print("Saved successfully")
    } catch _ {
        print("there was issue saving data!")
    }

}