2014-07-08 115 views
0

我試圖獲取「內容」的字符串,但是當我執行代碼時,應用程序崩潰...當我嘗試使用self.content.text = "\(theText)"它可以工作,但我想編碼爲UTF8,因爲我使用cyrilic和我回來這種\U0421\U044a\U0434\U044a\U0440\U0436\U0430\U043d\U0438\U0435 \U043d\U0430 \U043f\U0438\U0449\U043e\U0432\U0430誰能解決這個問題?Swift - 從核心數據獲取字符串並轉換爲UTF8

下面是代碼:

 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 

回答

2

這已無關的編碼問題。

  • 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 
} 
+0

謝謝你的工作:) –