2017-04-02 59 views
2

我的類中有一種從coredata中提取數據的方法。但我有一個問題:我需要將結果轉換爲數組,因爲那樣我就不得不在另一個類中使用該數組。iOS:將coredata獲取到數組並傳遞給另一個類的結果

的方法是:

func loadQuestion() -> NSArray{ 
     let fetchRequest: NSFetchRequest<Questions> = Questions.fetchRequest() 

     do { 
      let array = try self.context.fetch(fetchRequest) as NSArray 
      guard array.count > 0 else { print("[EHY!] Non ci sono elementi da leggere "); return array } 

      return array 
     } catch let errore { 
      print("error FetchRequest") 
     } 

     return list 
    } 

我無法弄清楚如何將變量數組轉換?

結果(錯誤)

enter image description here

編輯:我寫這篇文章,因爲我想要的結果轉換的讀取到 一個數組,這樣你就可以切換到另一個類

+0

@TusharSharma我在另一個類中定義一樣的數組:'VAR數組:NSArray的= []'因爲我想陣列從類通過其中I'loadQuestion()'函數到另一個類。 – Taprolano

+0

然後我寫了(在我想要數組的類中)'array = loadQuestion()CoreDataController。共享「 獲取該數組,然後」打印(數組)「打印內容。問題是它不打印確切的數據,但記憶和錯誤 – Taprolano

+0

[iOS Core Data:將獲取請求的結果轉換爲數組]的可能重複(http://stackoverflow.com/questions/35686273/ios- core-data-convert-fetch-request-to-an-array) – 2017-04-02 20:36:41

回答

2

fetch返回(可選)數組,因此您只需從函數中返回該數組即可。由於fetchthrows您的函數應該是throw或至少返回一個可選項,因爲提取可能會失敗。

在Swift中很少需要使用NSArray;一個正確類型的Swift數組將使你的代碼更清晰和更安全。由於Swift中的CoreData支持泛型,fetch將根據您的NSFetchRequest自動返回適當的數組類型。即使你從Objective-C中調用這個函數,最好讓編譯器將Swift數組橋接到NSArray

最後,你錯誤地使用了guard;如果它有0個項目,則嘗試返回array,否則返回一些變量list,該變量未在您顯示的代碼中聲明。

func loadQuestion() -> [Questions]? { 
    let fetchRequest: NSFetchRequest<Questions> = Questions.fetchRequest() 

    do { 
     let array = try self.context.fetch(fetchRequest) as [Questions] 
     return array 
    } catch let errore { 
     print("error FetchRequest \(errore)") 
    } 

    return nil 
} 
+0

哇...............工作! – Taprolano

相關問題