【发布时间】:2018-03-06 09:10:45
【问题描述】:
我第一次在 swift 中遇到这个非常奇怪的问题。我在 json 中有 8 个值。通过服务,我正在解析该 json 并将这些值保存在 coreData 中。所有 8 个值都被保存。但是当我从该表中获取值时。它有时会返回 4 个值或 5 或 3 个值,例如随机但不是全部。我什至没有应用任何谓词。我被严重卡住了,因为我无法理解这个问题。
这就是我在 CoreData 中保存它的方式:
for field in json as? [AnyObject] ?? [] {
self.SaveDayViewDetails(monthlyid: (field["MonthlyID"] as! String), mioauthid: (field["MIOAuthID"] as! String), empid: (field["EmpID"] as! String), doctorid: (field["DoctorID"] as! String))
}
class func SaveDayViewDetails (monthlyid: String, mioauthid: String, empid : String,doctorid : String,doccode : String,callplanneractivityid : String,actid : String,startdate : String,speciality : String,s3 : String,s2 : String,s1 : String,plannerid : String,p4 : String,p3 : String,p2 : String,p1 : String,mstatus : String,miostatusreason : String,miostatus : String,miodescription : String,isexecuted : String,g1 : String,end_date : String,doctorname : String,classname : String,address : String,actname : String,actfcolor : String,actbcolor : String,editable : String,planmonth : String,date:String) {
let context = getContext()
let privateMOC = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
privateMOC.parent = context
//retrieve the entity that we just created
let entity = NSEntityDescription.entity(forEntityName: "Tbl_SchedularDayView", in: context)
let transc = NSManagedObject(entity: entity!, insertInto: context)
//set the entity values
transc.setValue(Int32(monthlyid), forKey: "monthlyid")
transc.setValue(mioauthid, forKey: "mioauthid")
transc.setValue(Int32(empid), forKey: "empid")
transc.setValue(Int32(doctorid), forKey: "doctorid")
//save the object
do {
try privateMOC.save()
context.performAndWait {
do {
try context.save()
print("total saved Tbl_SchedularDayView in Database!")
} catch {
fatalError("Failure to save context: \(error)")
}
}
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
这就是我获取它的方式:
var drname:[String] = []
let fetchRequest1:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Tbl_SchedularDayView") // 2nd
do{
let searchResults = try ServiceCalls.getContext().fetch(fetchRequest1)
for trans in searchResults as! [NSManagedObject] {
drname.append(trans.value(forKey: "mioauthid") as! String)
}
}catch {
print("Error with request: \(error)")
}
print("total docs 1 = ",drname.count," doc names = ",drname)
【问题讨论】:
标签: ios database xcode core-data swift3