我试图获取“content”的字符串,但是当我执行代码时,应用程序崩溃。。。当我尝试使用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

最佳答案

这与编码问题无关。
executeFetchRequest()返回托管对象数组。
对该数组应用valueForKey()将返回一个值数组。
打印数组的描述时,对所有
非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
}

10-08 09:26