【问题标题】:Swift - Get String From Core Data And Converted In UTF8Swift - 从核心数据中获取字符串并转换为 UTF8
【发布时间】:2014-07-08 14:31:01
【问题描述】:

我正在尝试获取“内容”的字符串,但是当我执行代码时应用程序崩溃......当我尝试使用 self.content.text = "\(theText)" 它工作但我想编码为 UTF8,因为我使用西里尔字母,然后我回来了这些\U0421\U044a\U0434\U044a\U0440\U0436\U0430\U043d\U0438\U0435 \U043d\U0430 \U043f\U0438\U0449\U043e\U0432\U0430 有谁能解决这个问题吗?

代码如下:

     let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        let context: NSManagedObjectContext = appDel.managedObjectContext
        let theReq = NSFetchRequest(entityName: "Entity1")
        theReq.returnsObjectsAsFaults = false
        let myPredicate = NSPredicate(format: "objectId == \"\(contentID)\"")
        theReq.predicate = myPredicate
        let executed:AnyObject = context.executeFetchRequest(theReq, error: nil) as Array
        let theText : AnyObject = executed.valueForKey("content")
        self.content.text = theText

【问题讨论】:

    标签: string core-data swift


    【解决方案1】:

    这与编码问题无关。

    • executeFetchRequest() 返回托管对象的数组
    • valueForKey() 应用于该数组会返回一个数组 值。
    • 打印数组的 描述 对所有数组使用 \Unnnn 转义序列 非 ASCII 字符。

    所以解决方案应该很简单:选择获取的数组的单个元素:

    let executed = context.executeFetchRequest(theReq, error: nil)[0] as NSManagedObject
    let theText = executed.valueForKey("content") as String
    self.content.text = theText
    

    当然还要检查获取是成功还是失败,以及是否返回 任何物体。更详细的版本如下所示:

    var error : NSError?
    let result = context.executeFetchRequest(theReq, error: &error)
    if !result  {
        println("fetch failed: \(error)")
    } else if result.count == 0 {
        println("nothing found")
    } else {
        let obj = result[0] as NSManagedObject
        let theText = obj.valueForKey("timeStamp") as String
        self.content.text = theText
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-26
      • 2019-04-14
      • 1970-01-01
      • 2014-05-20
      • 1970-01-01
      • 1970-01-01
      • 2020-10-11
      • 1970-01-01
      相关资源
      最近更新 更多