swift - 获取实体的函数仅在从 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
}
解决方案
推荐阅读
- r - 为什么 R system() 命令杀死端口进程也会杀死 Ubuntu 19.10 Rstudio 会话?
- javascript - 无法使用 Protractor Azure Pipeline 运行 conf.js
- python - 在编译像这样的“NoneType”对象没有属性“find_all”的代码时出现错误
- gcc - gcc builtins 的源代码在哪里?
- ios - 如何让 iOS 模拟器在 macOS 中始终保持领先
- angular - Angular Unit Testing- Mocking of Service in component
- c++ - 您如何使用模板类专门化模板化函数?
- macos - dyld: Library not loaded: /usr/local/opt/isl/lib/libisl.21.dylib
- css - 使用列表中的值作为选择器 SCSS
- google-app-engine - Intermittent errors that go away after a few minutes