ios - Fetch Request 执行方法不返回任何内容

标签 ios database swift core-data appdelegate

在我的应用程序中,我使用 Core Data 来保存有关用户的一些基本信息,并轻松获取我创建的数据 Assistant类有一些静态函数。其中之一如下:

static func fetchData(forEntity name: String) -> AnyObject{

        var result: AnyObject!

        let dataController = DataController().managedObjectContext
        let fetchRequest = NSFetchRequest(entityName: name)

        do{
            result = try dataController.executeFetchRequest(fetchRequest)
        }catch{
            print("Failed to execute fetch request for \(name) entity")
        }
        print("Returning result: \(result.description)")

        return result
    }

问题是当我使用它时print("Returning result: \(result.description)")打印“返回结果:()”,它不是零,它只是一个空 AnyObject我假设。无论如何,如果我在这个方法中使用它:

static func getName() -> String{

        let fetched = fetchData(forEntity: "UserData") as! [UserData]

        if fetched.count > 0{
            print("Returning found value: \(fetched.first!.username!)")
            return fetched.first!.username!
        }else{
            print("Did not find any data, returning an empty string")
            return ""
        }

    }

它返回一个空字符串。但是,如果我在另一个类中使用以下方法:

func initialize(){

        do{
            let fetch = NSFetchRequest(entityName: "UserData")
            let entities = try dataController.executeFetchRequest(fetch) as! [UserData]
            if entities.count > 0{
                dispatch_async(dispatch_get_main_queue(), {self.fld_name.text = entities[0].username})
            }else{
                dispatch_async(dispatch_get_main_queue(), {self.fld_name.text = ""})
            }
        }catch{
            print("Nope, nothing's here")
        }

    }

它工作得很好,数据读取正确。 以下是您需要了解的内容:我使用 getName() AppDelegate中的方法的application(application:, didFinishLaunchingWithOptions launchOptions:)方法。所以可能是 CoreData 此时无法正常工作(我严重怀疑)

好的,这是我的假设:

  1. 这个问题可能是因为返回AnyObject而出现的因此我丢失了所有数据?
  2. 可能是因为 CoreData 此时尚未(以某种方式)激活吗?
  3. 这只是我犯的一些愚蠢的错误吗?

请提出您的解决方案。预先感谢您!

最佳答案

您遇到一些可能会导致麻烦的问题。首先,我将重写您的 fetchData 函数。

static func fetchData(forEntity name: String) -> [AnyObject] {

    let dataController = DataController().managedObjectContext
    let fetchRequest = NSFetchRequest(entityName: name)

    do{
        let results = try dataController.executeFetchRequest(fetchRequest)
        print("Returning result: \(results.description)")
        return results
    } catch {
        print("Failed to execute fetch request for \(name) entity")
        return []
    }
}

exexuteFetchRequest的返回类型是一个AnyObjectArray,而不仅仅是一个。

对于您的 getName() 函数,我将执行以下操作。它使用 if let 绑定(bind)来安全地处理您的结果。

static func getName() -> String {

    if let 
        fetched = fetchData(forEntity: "UserData") as? [UserData],
        userData = fetched.first,
        username = userData.username {
        print("Returning found value: \(username)")
        return username  
    } else {
        print("Did not find any data, returning an empty string")
        return ""
    }
}

尝试一下,看看是否有帮助。至少,这段代码更加安全,并且如果出现任何问题,崩溃的可能性也小得多。

关于ios - Fetch Request 执行方法不返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34512571/

相关文章:

ios - Apple Pay 的服务器端支付 token 解密

html - 短信 : and mailto: failure on iPhone Safari Mobile Browser

MySQL:根据另一行更新多行的列

ios - 谷歌地图打破业务逻辑单元测试

ios - 在 UITextField 之外的任何地方触摸时关闭键盘

iphone - 核心图形透明覆盖

mysql - 选择SUM达到700的记录

sql - Oracle SQL 多表插入语句

swift - 通过 Alamofire 集成 salesforce api?

swift - 将字典数组转换为集合 Swift 4