当UITableView为空时,无法获取CoreData属性值

时间:2017-08-15 00:11:10

标签: ios swift core-data

我有一个应用程序,每次使用刷卡删除tableviewcell函数时,它会将金额5添加到我的核心数据属性值。核心数据配置如下所示:https://i.stack.imgur.com/16YR6.png commit editingStyle类中的代码如下所示:

    if editingStyle == UITableViewCellEditingStyle.delete{

        let fetchRequest: NSFetchRequest<Goal> = Goal.fetchRequest()
        do {
            let array_users = try context.fetch(fetchRequest)

            let user = array_users[0]
            var count: Int64 = user.value(forKey: "totalGold") as! Int64
            count += 5
            user.setValue(count, forKey: "totalGold")
            let str = String(describing: user.value(forKey: "totalGold") as! Int64)
            totalGold.text = str
            do {
                try context.save()
                print("saved!")
            } catch let error as NSError  {
                print("Could not save \(error), \(error.userInfo)")
            } catch {

            }

             }

            catch {
            print("Error with request: \(error)")
            }
let managedObject: NSManagedObject = controller.object(at: indexPath) as NSManagedObject;
        context.delete(managedObject)
        ad.saveContext()
    }
}

然后我在viewDidLoad中使用相同的提取过程,如下所示:

let fetchRequest: NSFetchRequest<Goal> = Goal.fetchRequest()
    do {

        let array_users = try context.fetch(fetchRequest)

        let user = array_users[0]
        let count: Int64 = user.value(forKey: "totalGold") as! Int64
        user.setValue(count, forKey: "totalGold")
        let str = String(describing: user.value(forKey: "totalGold") as! Int64)
        totalGold.text = str




        //save the context
        do {
            try context.save()
            print("saved!")
        } catch let error as NSError  {
            print("Could not save \(error), \(error.userInfo)")
        } catch {

        }

        } catch {
        print("Error with request: \(error)")
    }

除非表视图中没有表格视图单元格,否则此代码适用于所有情况。然后,当我尝试在没有单元格的情况下重新加载视图时,在尝试获取该行时,我得到索引超出范围错误:

 let user = array_users[0]

显然,这是因为当我尝试获取totalGold的最新值时,它无法找到它并且它认为没有值,所以我做错了。如何正确获取totalGold的最新属性值?

1 个答案:

答案 0 :(得分:0)

你可以把那些放在条件

let fetchRequest: NSFetchRequest<Goal> = Goal.fetchRequest()
    do {
        let array_users = try context.fetch(fetchRequest)
        if array_users.count > 0 {
            let user = array_users[0]
            let count: Int64 = user.value(forKey: "totalGold") as! Int64
            user.setValue(count, forKey: "totalGold")
            let str = String(describing: user.value(forKey: "totalGold") as! Int64)
            totalGold.text = str

            //save the context
            do {
                try context.save()
                print("saved!")
            } catch let error as NSError  {
                print("Could not save \(error), \(error.userInfo)")
            } catch {
            }
        }
    } catch {
        print("Error with request: \(error)")
    }