2016-06-09 44 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版本編輯你的答案好嗎? –