I am getting a certain value called productId
from the api. I want to store this value in Core-Data so that I can use this in another view-controller.
我从api获得了一个名为productId的值。我想将此值存储在Core-Data中,以便我可以在另一个视图控制器中使用它。
So when I'm getting the productID
from the api, this is how I'm saving it...
所以当我从api获取productID时,这就是我如何保存它...
....else if result["success"] as! Int == 1 {
print("SUCCESS!!")
self.productId = (result["product_id"] as! NSString) as String
self.saveId(givenName: self.productId) //Saving here...
}
In the saveId
function, this is what I'm doing...
在saveId函数中,这就是我正在做的......
func saveName(givenName:String) {
//Saving to CoreData
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Category", in: managedContext)
let category = NSManagedObject(entity: entity!, insertInto: managedContext)
category.setValue(givenName, forKey: "productId")
do {
try managedContext.save()
self.mangObjArr.append(category as! Category)
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
This is not working because in viewWillAppear
when I fetch the data, I'm getting nil for productId
. This is what I'm doing in viewWillAppear
...
这不起作用,因为在viewWillAppear中,当我获取数据时,我的productId为零。这就是我在viewWillAppear中所做的...
override func viewWillAppear(_ animated: Bool) {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Category")
if let fetchedObjects = try? managedContext.fetch(fetchRequest), !fetchedObjects.isEmpty
{
let category = fetchedObjects.first as? NSManagedObject
self.theProductId = category?.value(forKey: "productId") as! String
print(theProductId)
}
Hope somebody can help...:)
希望有人能帮忙...... :)
1 个解决方案
#1
0
You are fetching the data from CoreData of entity category. Check whether category object is nil or not before checking the productId.
您正在从实体类别的CoreData获取数据。在检查productId之前,检查类别对象是否为零。
If your category object is nil than it is obvious that productId is nil and this is because your fetching category from CoreDB and there is no record for that entity.
如果你的category对象是nil,那么很明显productId是nil,这是因为你从CoreDB获取类别并且没有该实体的记录。
Hope you understand.
希望你能理解。
Save data before fetch will return you some record.
在获取之前保存数据将返回一些记录。
#1
0
You are fetching the data from CoreData of entity category. Check whether category object is nil or not before checking the productId.
您正在从实体类别的CoreData获取数据。在检查productId之前,检查类别对象是否为零。
If your category object is nil than it is obvious that productId is nil and this is because your fetching category from CoreDB and there is no record for that entity.
如果你的category对象是nil,那么很明显productId是nil,这是因为你从CoreDB获取类别并且没有该实体的记录。
Hope you understand.
希望你能理解。
Save data before fetch will return you some record.
在获取之前保存数据将返回一些记录。