2017-05-30 6 views
1

私のコアデータテーブルには、このようなものです。その結果は次のようにする必要があります:は明確な結果がコアデータから一つのフィールドに基づいて取得する方法を

enter image description here

これは私のコードです:

NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"MyCoreDataObject" inManagedObjectContext:moc]; 
    NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"MESSAGE <> ''"]; 

    request.predicate = predicate; 
    NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"TIME" ascending:NO]; 
    NSArray *sortDescriptors = @[sd1]; 
    [request setSortDescriptors:sortDescriptors]; 
    [request setEntity:entityDescription]; 
    NSError *error; 
    NSArray *msgs = [moc executeFetchRequest:request error:&error]; 

私はすべてのソートされたデータ(最初に最新のメッセージ)を取得します。 しかし、送信者に基づいて一意の値を取得するにはどうすればよいですか?各送信者の最新のメッセージのみ?

基本的に私は、このSQLの同等のものが必要です。

SELECT message, sender, MAX(time) as maxTime FROM myTable GROUP BY sender; 

答えて

1

は、メッセージフィールドの取得が難しい部分でした。

基本的にgroup byを使用すると、(送信者)でグループのプロパティを取得し、式(時間)でプロパティを取得できます。

他のすべての値を取得するには、フェッチされた値(送信者と時刻)を使用し、別のフェッチを実行してコアデータから取得する必要があります。

NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"MyCoreDataObject" inManagedObjectContext:moc]; 
NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"message <> ''"]; 

request.predicate = predicate; 
NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"time" ascending:NO]; 
NSArray *sortDescriptors = @[sd1]; 
[request setSortDescriptors:sortDescriptors]; 
[request setEntity:entityDescription]; 

NSExpressionDescription *timestampExp = [[NSExpressionDescription alloc] init]; 
[timestampExp setExpression:[NSExpression expressionWithFormat:@"@max.time"]]; 
[timestampExp setName:@"time"]; 
[timestampExp setExpressionResultType:NSDateAttributeType]; 

[request setSortDescriptors:sortDescriptors]; 
[request setEntity:entityDescription]; 
[request setResultType:NSDictionaryResultType]; 
[request setPropertiesToGroupBy:[NSArray arrayWithObject:@"sender"]]; 
[request setPropertiesToFetch:[NSArray arrayWithObjects:@"sender", timestampExp, nil]]; 

NSError *error; 
NSArray *msgs = [moc executeFetchRequest:request error:&error]; 
for (NSDictionary *msg in msgs) { 
    request = [[NSFetchRequest alloc] init]; 
    predicate = [NSPredicate predicateWithFormat:@"message <> '' and sender = %@ and time = %@ ", msg[@"sender"], msg[@"time"]]; 

    request.predicate = predicate; 
    [request setSortDescriptors:sortDescriptors]; 
    [request setEntity:entityDescription]; 
    NSDictionary *myMessage = [moc executeFetchRequest:request error:&error][0]; 

} 
関連する問題