加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift获取请求返回结果中的空项

发布时间:2020-12-14 05:29:52 所属栏目:百科 来源:网络整理
导读:我有一个项目,我需要做一个获取请求,获取核心数据实体的最新“更新”日期.当我实际检查查询返回的结果时,我看到一些相当奇怪的行为.除了包含日期的“正确”结果外,结果还包括空字典项.无论底层数据是什么样的,每次都会发生这种情况.更奇怪的是,如果我在 xcod
我有一个项目,我需要做一个获取请求,获取核心数据实体的最新“更新”日期.当我实际检查查询返回的结果时,我看到一些相当奇怪的行为.除了包含日期的“正确”结果外,结果还包括空字典项.无论底层数据是什么样的,每次都会发生这种情况.更奇怪的是,如果我在 xcode中打开sql登录并对sqllite db执行记录查询,它会产生正确的结果而没有额外的条目.我不太确定我在这里做错了什么,任何帮助都会受到赞赏.

构建和执行查询的函数:

func queryForContactDate(context:NSManagedObjectContext) -> AnyObject?
{

    var expressionDescriptions = [AnyObject]();

    let expressionDescription = NSExpressionDescription()

    // Name the column
    expressionDescription.name = "maxUpdated"
    // Use an expression to specify what aggregate action we want to take and
    // on which column. In this case max on the update_at column
    expressionDescription.expression = NSExpression(format: "@max.updated_at")
    // Specify the return type we expect
    expressionDescription.expressionResultType = .DateAttributeType
    // Append the description to our array
    expressionDescriptions.append(expressionDescription)

    // Build out our fetch request the usual way
    let request = NSFetchRequest(entityName: Contact.entityName())

    // Specify we want dictionaries to be returned
    request.resultType = .DictionaryResultType

    // Hand off our expression descriptions to the propertiesToFetch field.
    request.propertiesToFetch = expressionDescriptions

    // Our result is going to be an array of dictionaries.
    var results:[[String:AnyObject]]?

    // Perform the fetch. This is using Swfit 2,so we need a do/try/catch
    do {
        results = try context.executeFetchRequest(request) as? [[String:AnyObject]]
    } catch _ {
        // If it fails,ensure the array is nil
        results = nil
    }

    return results![0];
}

如果我在最后放置一个断点并打印出它产生的结果:

Printing description of results:
? Optional([[:],["maxUpdated": 2015-12-30 20:05:31 +0000]])
  ? Some : 2 elements
    - [0] : 0 elements
    ? [1] : 1 elements
      ? [0] : 2 elements
        - .0 : "maxUpdated"
        - .1 : 2015-12-30 20:05:31 +0000
获取最大或最小项目的传统Core Data方法是使用提取限制1进行查询并对该键进行排序.与此Objective-C代码一样:
+ (NSFetchRequest *) requestForStatusWithMaxID {

    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName: kAMStatusEntity];

    NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey: kAMTwID ascending:NO];

    request.sortDescriptors = @[sd];
    request.fetchLimit = 1;

    return request;

} // +requestForStatusWithMaxID

修改upd_at属性的上述内容非常简单.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读