[英]Coredata not giving data on fetch request
在我啟動我的應用程序時,我從coredata獲取數據。 它沒有給我數據。
但是,如果我沒有關閉我的應用程序並在數據庫中保存一些數據,並且如果我獲取數據會給我一個數據而沒有關閉我的應用程序。
當我關閉我的應用程序時。 下次再次沒有給我數據。
這是我的代碼
self.FetchAllLocalData({ (Available) in
if (Available == "0")
{
for ValueToSave in detailArray!
{
let entity = NSEntityDescription.insertNewObjectForEntityForName("RxOrder", inManagedObjectContext: moc)
print(ValueToSave.id!)
var medicinetype : String = ""
let Id : String = ValueToSave.id!.description
let isRx : String = ValueToSave.isRxMedicine!.description
print(ValueToSave.medicineTypeId)
if (ValueToSave.medicineTypeId != nil)
{
medicinetype = ValueToSave.medicineTypeId!
}
else
{
medicinetype = "0"
}
let medicineName : String = ValueToSave.name!
let orderId : String = ValueToSave.orderId!.description
let price : String = "0"
let quantity : String = ValueToSave.quentity!.description
let strength : String = ValueToSave.strength!
entity.setValue(Id, forKey: "medicineId")
entity.setValue(isRx, forKey: "isRxMedicine")
entity.setValue(medicinetype, forKey: "medicineType")
entity.setValue(medicineName, forKey: "productName")
entity.setValue(self.order_id_RX_Medicine!, forKey: "OrderId")
entity.setValue(price, forKey: "price")
entity.setValue(quantity, forKey: "quantity")
entity.setValue(strength, forKey: "strength")
do{
try moc.save()
}
catch {
fatalError("failed To Save Content\(error)")
}
}
而這個拿來
func FetchAllLocalData(completion : (Available : String)-> Void) {
let request : NSFetchRequest = NSFetchRequest(entityName: "RxOrder")
do{
//request.predicate = NSPredicate(format: "orderId == \(order_id_RX_Medicine!)")
let fetchedPerson = try moc.executeFetchRequest(request)
DataAvailable = fetchedPerson as! [NSManagedObject]
print(DataAvailable.count)
if (DataAvailable.count > 0)
{
print(DataAvailable[0].valueForKey("orderId"))
for OldData in DataAvailable {
print(DataAvailable.count)
print(order_id_RX_Medicine)
print(OldData.valueForKey("orderId"))
if (OldData.valueForKey("orderId")! as! String == order_id_RX_Medicine)
{
completion(Available: "1")
}
else
{
completion(Available: "0")
}
}
}
else
{
completion(Available: "0")
}
}
catch
{
completion(Available: "0")
fatalError("Something Went Wrong \(error)")
}
}
首先,由於您在此處並且代碼中包含print
語句,因此我假設您看到了那些火災,並且在您的應用程序運行時沒有出現錯誤。
因此,查看您的核心數據創建代碼將很有幫助。
查看如何將moc
納入創建代碼也將很有幫助。 創建代碼位於AppDelegate還是其他地方?
您正在使用哪種類型的持久性存儲?
您必須在您的應用程序委托中嘗試以下操作:
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
AppDelegate.shared.saveContext()
}
這將在應用終止之前保存您的數據
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.