草庐IT

关于ios:Fetching selected attribute in entity

codeneng 2023-03-28 原文

Fetching selected attribute in entities

我有一个具有多个属性的核心数据实体,我想要一个属性中所有对象的列表。我的代码如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
        let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        let context:NSManagedObjectContext = appDel.managedObjectContext!

        let sortDesc = NSSortDescriptor(key:"username", ascending: true)

        let fetchReq = NSFetchRequest(entityName:"Identities")
        fetchReq.sortDescriptors = [sortDesc]
        fetchReq.valueForKey("username")

        let en = NSEntityDescription.entityForName("Identities", inManagedObjectContext: context)

        userList = context.executeFetchRequest(fetchReq, error: nil) as [Usernames]

但这给了我一个 NSException 错误,我不知道为什么,或者我应该怎么做。我已经阅读了 NSFetchRequest 类的描述,但无法理解它。

任何建议都将不胜感激。

编辑:收到 Bluehound 的提示后,我将代码更改为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var userList = [Model]()
@IBAction func printUsers(sender: AnyObject) {
    let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    let context:NSManagedObjectContext = appDel.managedObjectContext!

    let sortDesc = NSSortDescriptor(key:"friendID", ascending: true)

    let fetchReq = NSFetchRequest(entityName:"Identities")
    fetchReq.sortDescriptors = [sortDesc]
    fetchReq.propertiesToFetch = ["friendID"]

    let en = NSEntityDescription.entityForName("Identities", inManagedObjectContext: context)

    userList = context.executeFetchRequest(fetchReq, error: nil) as [Model]

    println(userList)

}

运行时错误消失了,但我仍然不知道它是否有效,因为我不确定如何将列表转换为字符串列表。

一如既往,我们将不胜感激。

  • 使用 NSFetchRequest\\ 的 propertiesToFetch 属性而不是 valueForKey
  • @Bluehound 你能告诉我吗,我在初始化 NSPropertyDescription 时遇到了麻烦。
  • println(userList) 的输出是什么样的?
  • @pbasdf [ , , ] 与我获取整个班级时相同。
  • 行。尝试添加 fetchReq.resultType = .DictionaryResultType
  • @pbasdf 这在 println 函数中给我一个错误,说 NSArray 元素无法匹配 Swift Array 元素类型。
  • 哦,对不起,将 as [Model] 更改为 as [AnyObject]


有两种可能:可以发出正常的fetch请求
并从结果中提取包含所需属性的数组,
使用 map():

1
2
3
4
5
6
7
8
9
10
let fetchReq = NSFetchRequest(entityName:"Identities")
fetchReq.sortDescriptors = [sortDesc]

var error : NSError?
if let result = context.executeFetchRequest(fetchReq, error: &error) as? [Model] {
    let friendIDs = map(result) { $0.friendID }
    println(friendIDs)
} else {
    println("fetch failed: \\(error!.localizedDescription)")
}

斯威夫特 2:

1
2
3
4
5
6
7
8
9
10
let fetchReq = NSFetchRequest(entityName:"Identities")
fetchReq.sortDescriptors = [sortDesc]

do {
    let result = try context.executeFetchRequest(fetchReq) as! [Model]
    let friendIDs = result.map { $0.friendID }
    print(friendIDs)
} catch let error as NSError {
    print("fetch failed: \\(error.localizedDescription)")
}

或者您将 resultType 设置为 .DictionaryResultType
propertiesToFetch 到想要的属性。
在这种情况下,获取请求将返回一个字典数组:

1
2
3
4
5
6
7
8
9
10
11
12
let fetchReq = NSFetchRequest(entityName:"Identities")
fetchReq.sortDescriptors = [sortDesc]
fetchReq.propertiesToFetch = ["friendID"]
fetchReq.resultType = .DictionaryResultType

var error : NSError?
if let result = context.executeFetchRequest(fetchReq, error: &error) as? [NSDictionary] {
    let friendIDs = map(result) { $0["friendID"] as String }
    println(friendIDs)
} else {
    println("fetch failed: \\(error!.localizedDescription)")
}

斯威夫特 2:

1
2
3
4
5
6
7
8
9
10
11
12
let fetchReq = NSFetchRequest(entityName:"Identities")
fetchReq.sortDescriptors = [sortDesc]
fetchReq.propertiesToFetch = ["friendID"]
fetchReq.resultType = .DictionaryResultType

do {
    let result = try context.executeFetchRequest(fetchReq) as! [NSDictionary]
    let friendIDs = result.map { $0["friendID"] as! String }
    print(friendIDs)
} catch let error as NSError {
    print("fetch failed: \\(error.localizedDescription)")
}

第二种方法的优点是只有指定的属性
从数据库中获取,而不是从整个托管对象中获取。

它的缺点是结果不包含pending
托管对象上下文中未保存的更改(includesPendingChanges:
使用 .DictionaryResultType 时隐式设置为 false).

  • 我从您问题中的代码中获取了实体名称"Identities"和托管对象子类的名称"Model"。通常人们会为两者使用相同的名称。
  • 再次感谢 Martin,您永远不会失望 :) 是的,我知道名称不是最佳的,它只是我很久以前创建的"测试项目"。

有关关于ios:Fetching selected attribute in entity的更多相关文章

  1. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  2. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  3. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  4. ruby - 为什么不能使用类IO的实例方法noecho? - 2

    print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上

  5. ruby-on-rails - 关于 Ruby 的一般问题 - 2

    我在我的rails应用程序中安装了来自github.com的acts_as_versioned插件,但有一段代码我不完全理解,我希望有人能帮我解决这个问题class_eval我知道block内的方法(或任何它是什么)被定义为类内的实例方法,但我在插件的任何地方都找不到定义为常量的CLASS_METHODS,而且我也不确定是什么here,并且有问题的代码从lib/acts_as_versioned.rb的第199行开始。如果有人愿意告诉我这里的内幕,我将不胜感激。谢谢-C 最佳答案 这是一个异端。http://en.wikipedia

  6. ruby - 我怎样才能更好地了解/了解更多关于 Ruby 的知识? - 2

    按照目前的情况,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visitthehelpcenter指导。关闭9年前。我最近开始学习Ruby,这是我的第一门编程语言。我对语法感到满意,并且我已经完成了许多只教授相同基础知识的教程。我已经写了一些小程序(包括我自己的数组排序方法,在有人告诉我谷歌“冒泡排序”之前我认为它非常聪明),但我觉得我需要尝试更大更难的东西来理解更多关于Ruby.关于如何执行此操作的任何想法?

  7. ruby - 关于 Ruby 中 Dir[] 和 File.join() 的混淆 - 2

    我在Ruby中遇到了一个关于Dir[]和File.join()的简单程序,blobs_dir='/path/to/dir'Dir[File.join(blobs_dir,"**","*")].eachdo|file|FileUtils.rm_rf(file)ifFile.symlink?(file)我有两个困惑:首先,File.join(@blobs_dir,"**","*")中的第二个和第三个参数是什么意思?其次,Dir[]在Ruby中有什么用?我只知道它等价于Dir.glob(),但是,我对Dir.glob()确实不是很清楚。 最佳答案

  8. elasticsearch源码关于TransportSearchAction【阶段三】 - 2

    1.回顾.TransportServicepublicclassTransportServiceextendsAbstractLifecycleComponentTransportService:方法:1publicfinalTextendsTransportResponse>voidsendRequest(finalTransport.Connectionconnection,finalStringaction,finalTransportRequestrequest,finalTransportRequestOptionsoptions,TransportResponseHandlerT>

  9. 关于Qt程序打包后运行库依赖的常见问题分析及解决方法 - 2

    目录一.大致如下常见问题:(1)找不到程序所依赖的Qt库version`Qt_5'notfound(requiredby(2)CouldnotLoadtheQtplatformplugin"xcb"in""eventhoughitwasfound(3)打包到在不同的linux系统下,或者打包到高版本的相同系统下,运行程序时,直接提示段错误即segmentationfault,或者Illegalinstruction(coredumped)非法指令(4)ldd应用程序或者库,查看运行所依赖的库时,直接报段错误二.问题逐个分析,得出解决方法:(1)找不到程序所依赖的Qt库version`Qt_5'

  10. ruby - 为 IO::popen 拯救 "command not found" - 2

    当我将IO::popen与不存在的命令一起使用时,我在屏幕上打印了一条错误消息:irb>IO.popen"fakefake"#=>#irb>(irb):1:commandnotfound:fakefake有什么方法可以捕获此错误,以便我可以在脚本中进行检查? 最佳答案 是:升级到ruby​​1.9。如果您在1.9中运行它,则会引发Errno::ENOENT,您将能够拯救它。(编辑)这是在1.8中的一种hackish方式:error=IO.pipe$stderr.reopenerror[1]pipe=IO.popen'qwe'#

随机推荐