2016-06-09 25 views
2

嗨,我有一张表格,格式如下。从CoreData上的不同属性获取顶部1

我想建立一个历史视图,所以我需要来自不同用户的最后一条消息,按时间戳排序!

+---+-------------------+-------------------+---------------+ | | Username | Message | Timestamp | +---+-------------------+-------------------+---------------+ | 1 | John | Hello | 486380161.723 | | 2 | Mark | Spreadsheet | 486380264.723 | | 3 | John | FYI | 486380366.723 | | 4 | John | Bye | 486557497.271 | | 5 | Mark | How are you? | 486557597.274 | | 6 | Mario | What? | 486558597.274 | +---+-------------------+-------------------+---------------+

这是我的结果应该是什么。

+---+-------------------+-------------------+---------------+ | | Username | Message | Timestamp | +---+-------------------+-------------------+---------------+ | 6 | Mario | What? | 486558597.274 | | 5 | Mark | How are you? | 486557597.274 | | 4 | John | Bye | 486557497.271 | +---+-------------------+-------------------+---------------+

现在,我得到所有不同username,迭代每一个和查询该用户名中的消息,通过时间戳排序,limit(1)

我对这个解决方案不满意,所以任何人都可以帮助我做出更好的解决方案?

感谢, 马里奥

+0

CoreData不是关系数据库。它是一个对象持久化系统。也许你应该在SQLite中存储你的消息? – Paulw11

回答

3

这是可能做到这一点在两次存取,有一点需要注意,当我得到它,我会提到。

第一个读取获取用户名和最近的时间戳每个:

let maxTimestampRequest = NSFetchRequest(entityName: "Entity") 
    maxTimestampRequest.resultType = .DictionaryResultType 

    let maxTimestampExpression = NSExpression(format: "max:(timestamp)") 
    let maxTimestampExpressiondescription = NSExpressionDescription() 
    maxTimestampExpressiondescription.name = "maxTimestamp" 
    maxTimestampExpressiondescription.expression = maxTimestampExpression 
    maxTimestampExpressiondescription.expressionResultType = .DoubleAttributeType 

    maxTimestampRequest.propertiesToFetch = ["username", maxTimestampExpressiondescription] 
    maxTimestampRequest.propertiesToGroupBy = ["username"] 

执行,取指,你会得到字典的数组。每个字典都包含用户名和该用户名的最新时间戳:

Optional([{ 
    maxTimestamp = "486557497.271"; 
    username = John; 
}, { 
    maxTimestamp = "486558597.274"; 
    username = Mario; 
}, { 
    maxTimestamp = "486557597.274"; 
    username = Mark; 
}]) 

获取完整记录需要第二次获取。如果前面的结果fetch是在一个名为results阵列,

var predicates = [NSPredicate]() 
    for maxTimestampInfo in results! { 
     let username = maxTimestampInfo["username"]! 
     let timestamp = maxTimestampInfo["maxTimestamp"]! 
     let partialPredicate = NSPredicate(format: "username=%@ and timestamp=%@", argumentArray:[ username, timestamp ]) 
     predicates.append(partialPredicate) 
    } 
    let completePredicate = NSCompoundPredicate(orPredicateWithSubpredicates: predicates) 

    let fetch = NSFetchRequest(entityName: "Entity") 
    fetch.predicate = completePredicate 

执行取,你会得到满足您的要求,充分管理的对象。

需要注意的是,第二次读取中的谓词可能会非常大,具体取决于您拥有的用户数量。

+0

谢谢@Tom。该解决方案完美运作。我稍后会用Objc版本编辑你的答案好吗? –

相关问题