我正在使用 iphone 中的核心数据实现聊天数据库。我创建了两个实体聊天用户和聊天消息。并且chatuser 和chatmessgae 实体之间存在一对多的关系。对于一个聊天用户,可以有许多聊天消息。我正在存储数据
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Chatuser"
inManagedObjectContext:self.managedObjectContext];
[request setEntity:entity];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"chatuser == %@", chatuser];
[request setPredicate:pred];
NSArray *userArray=[self.managedObjectContext executeFetchRequest:request error:&error];
if ([userArray count] > 0){
Chatuser *user = [userArray objectAtIndex:0];
Chatmessage *message = [NSEntityDescription insertNewObjectForEntityForName:@"Chatmessage" inManagedObjectContext:self.managedObjectContext];
message.chatmessage = chatmessage;
[user addAllchatmessagesObject:message];
NSError *error;
if(![self.managedObjectContext save:&error])
{
NSLog(@"whoops, couldn't save: %@", [error localizedDescription]);
}
}
// }
else
{
Chatuser *user = [NSEntityDescription insertNewObjectForEntityForName:@"Chatuser" inManagedObjectContext:self.managedObjectContext];
user.chatuser = chatUser;
Chatmessage *message = [NSEntityDescription insertNewObjectForEntityForName:@"Chatmessage" inManagedObjectContext:self.managedObjectContext];
message.chatmessage = chatmessage;
[user addAllchatmessagesObject:message];
NSError *error;
if(![self.managedObjectContext save:&error])
{
NSLog(@"whoops, couldn't save: %@", [error localizedDescription]);
}
}
并以这种方式获取数据
managedObjectContext = appDelegate.managedObjectContext;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Chatuser" inManagedObjectContext:self.managedObjectContext];
[request setEntity:entity];
NSError *error;
NSPredicate *pred = [NSPredicate predicateWithFormat:@"chatuser == %@", appDelegate.chatUser];
[request setPredicate:pred];
NSArray *userinfo = [self.managedObjectContext executeFetchRequest:request error:&error];
if([userinfo count]>0)
{
Chatuser *user = [userinfo objectAtIndex:0];
NSSet *messageset = user.allchatmessages;
self.messageinfo = [messageset allObjects];
int message_count=[self.messageinfo count];
NSLog(@"Message count : %d", message_count);
for(int i=(message_count-1);i>=0;i--)
{
Chatmessage *chatmsgnew = [self.messageinfo objectAtIndex:i];
[tableArray addObject:chatmsgnew.chatmessage];
}
}
现在的问题是聊天消息没有按照我存储它们的顺序出现。就像我正在存储消息 1、2、3、4。并且在获取 2,1,4,3 的同时......我没有遇到问题。任何人都可以提出任何建议。