我的核心数据只存储一个数字到一个属性而不保存多个属性swift

时间:2016-08-08 01:59:30

标签: ios core-data swift2

我有一个应用程序来计算按下按钮的数量,我有一个数据库(coreData),我有一个属性num1和属性num2,当我运行应用程序核心数据将仅保存在属性num1或只有num2并给我另一个数字= 0

注意:我有一个变量i,因为当i = 0时,我希望核心数据保存到num1属性,如果i = 1,我希望核心数据保存到num2属性

我的保存方法如下:

func save()
{
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext
    //Data is in this case the name of the entity
    let entity = NSEntityDescription.entityForName("Mm",inManagedObjectContext: managedContext)

    let options = NSManagedObject(entity: entity!,insertIntoManagedObjectContext:managedContext)


    if (i == 0)
    {
      options.setValue(u, forKey: "num1")   
    }

    else if (i == 1)
    {
        options.setValue(u, forKey: "num2")    
    }
   do {
        try managedContext.save()
    } catch
    {
        print("error")
    }


}

我的阅读方法是:

func read()
{
    do
    {
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let managedContext = appDelegate.managedObjectContext
        let fetchRequest = NSFetchRequest(entityName: "Mm")

        let fetchedResults = try managedContext.executeFetchRequest(fetchRequest)

        var  j = fetchedResults.count-1

            let single_result = fetchedResults[j]
            let out = single_result.valueForKey("num1") as! NSNumber
            print("num1",out)
            let out1 = single_result.valueForKey("num2") as! NSNumber
            print("num2",out1)     
    }
    catch
    {
        print("error")
    }   
}

0 个答案:

没有答案