【问题标题】:get Double back from core data into text field从核心数据中获取 Double 返回到文本字段
【发布时间】:2017-02-08 00:56:05
【问题描述】:

我正在尝试将数字放入核心数据中,然后将它们取回。我已经可以使用字符串进行此操作,并且一切正常,但是尝试使用双打来进行操作似乎可以存储它们但不能检索它们。下面是我的代码。希望有人能帮忙,如果可以的话提前谢谢。

要检索...

    func getTranscriptions18CW () {

    let fetchRequest: NSFetchRequest<TextInputs> = TextInputs.fetchRequest()
    do {
        //go get the results
        let searchResults18CW = try getContext().fetch(fetchRequest)

        if indexPageSum == 18 {
            for trans in searchResults18CW as [NSManagedObject] {
                let result = trans.value(forKey: "cWeight")
                if result != nil {

                    CWeight.text = result! as? String
                }
            }
        }
    }catch {
        print("Error with request: \(error)")
    }
}

然后保存。

   func getContext () -> NSManagedObjectContext {
    _ = UIApplication.shared.delegate as! AppDelegate
    return DataController().managedObjectContext
}


func storeTranscription18CW (pageText: Double, textFileUrlString: String) {


    let context = getContext()

    //retrieve the entity that we just created
    let entity =  NSEntityDescription.entity(forEntityName: "TextInputs", in: context)

    let transc = NSManagedObject(entity: entity!, insertInto: context)

    // set the entity values
    if indexPageSum == 18 {
        transc.setValue(pageText, forKey: "cWeight")
    }
    //save the object
    do {
        try context.save()
        print("saved!")
    } catch let error as NSError  {
        print("Could not save \(error), \(error.userInfo)")
    } catch {

    }
}

然后保存另一部分。

 if indexPageSum == 18 {
                            let CWConvert = Double(CWeight.text!)
                            storeTranscription18CW(pageText: (CWConvert)!, textFileUrlString: "cWeight")

【问题讨论】:

    标签: swift string core-data double


    【解决方案1】:

    表达式:

    result! as? String
    

    基本上意味着“如果result 的类型为String,则返回它,否则返回nil”。这适用于存储在数据库中的Strings,但将nil 分配给CWeight.text 用于其他任何事情。

    你想要类似下面的东西:

    if let result = trans.value(forKey: "cWeight") {
        if let str = result as? String {
            CWeight.text = str
        }
        else {
            CWeight.text = "\(result)"
        }
    }
    

    这适用于最常见的数据类型。表达式"\(result)" 使用字符串插值将result 中存储的值转换为适当的字符串。

    您可能还想研究生成NSManagedObject 子类以使其更易于处理。

    【讨论】:

    • 嗨,谢谢您的帮助,这适用于我要保存的第一个,但是当我将它们全部 (8) 更改为具有不同名称的相同内容时,它只会保存最后一个作为其余的数字,我认为它与这部分有关....如果 indexPageSum == 18 { var CWConvert = Double(CWeight.text!) storeTranscription18CW(pageText: (CWConvert)!, textFileUrlString: "cWeight" ) CWConvert = Double(TWeight.text!) storeTranscription18TW(pageText: (CWConvert)!, textFileUrlString: "tWeight")
    • 你能把完整的代码贴在可以访问的地方吗?还是私下分享?看来这里可能还有其他事情需要解决。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    • 2016-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多