我编写了一个函数,该函数应该从某个实体获取所有对象,然后将所有一种属性放入数组中。奇怪的是,我的函数仅在从AppDelegate调用时才返回值?每当我尝试从其他地方调用它时,它只会返回一个空数组
import Foundation
import CoreData
import UIKit
func fetchAllFractions() -> [String] {
let appDelegate = UIApplication.shared.delegate as? AppDelegate
let context = appDelegate!.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Deputies")
var fractions: [String] = []
do {
let results = try context.fetch(fetchRequest) as! [Deputies] //Deputies is the Entity
print(results.count)
for deputy in results {
//check if the Array of fractions already containts the deputies fraction
if fractions.contains(deputy.fraction!) {
} else {
//if not, add it to the array
fractions.append(deputy.fraction!)
}
}
} catch let error {
print("Error Fetching Fractions", error)
}
print(fractions)
//return array of fractions
return fractions
}