首页 > 解决方案 > 获取实体的函数仅在从 AppDelegate 调用时有效

问题描述

我编写了一个函数,该函数应该从某个实体中获取所有对象,然后将各种属性放入一个数组中。奇怪的是,我的函数仅在从 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
}

标签: swiftfunctioncore-data

解决方案


推荐阅读