ngzhongcai
ngzhongcai

Reputation: 2043

Unable to get distinct attribute values from Core Data

2 functions below, but only one with results. In "noResult", I was trying to get a list of distinct attribute values, but all I get is {}.

-(void)noResult {
  NSManagedObjectContext *moc= [xmppMessageArchivingStorage mainThreadManagedObjectContext];
  NSEntityDescription *entity= [NSEntityDescription entityForName:@"XMPPMessageArchiving_Message_CoreDataObject" inManagedObjectContext:moc];
  NSFetchRequest *request= [[NSFetchRequest alloc] init];
  [request setEntity:entity];
  [request setResultType:NSDictionaryResultType];
  [request setReturnsDistinctResults:YES];
  [request setPropertiesToFetch:[NSArray arrayWithObject:@"contact"]];

  NSArray *messages= [moc executeFetchRequest:request error:nil];
  NSLog(@"%@", messages); 
}

-(void)gotResult {
   NSManagedObjectContext *moc= [xmppMessageArchivingStorage mainThreadManagedObjectContext];
   NSEntityDescription *entity= [NSEntityDescription entityForName:@"XMPPMessageArchiving_Message_CoreDataObject" inManagedObjectContext:moc];
   NSFetchRequest *request= [[NSFetchRequest alloc] init];
   [request setEntity:entity];
   NSArray *messages= [moc executeFetchRequest:request error:nil];
}

Below is from "gotResult" " (entity: XMPPMessageArchiving_Message_CoreDataObject; id: 0x1c5d7fc0 ; data: {\n bareJid = nil;\n bareJidStr = nil;\n body = \"Bean bags\";\n composing = 0;\n contact = 1000743469142;\n from = 7375011;\n message = nil;\n messageStr = nil;\n outgoing = 0;\n streamBareJidStr = nil;\n thread = nil;\n timestamp = \"2013-06-05 10:56:38 +0000\";\n})"

Upvotes: 0

Views: 234

Answers (1)

Martin R
Martin R

Reputation: 539795

The only reason for the different behaviour that I can think of is that you did not save the managed object context before calling the fetch request with NSDictionaryResultType.

[request setResultType:NSDictionaryResultType];

implies

[request setIncludesPendingChanges:NO];

and that means that the array returned from the fetch reflects the current state in the persistent store, and does not take into account any pending changes, insertions, or deletions in the context.

Upvotes: 2

Related Questions