SQLite记录未按照使用Core Data创建的顺序保存?

时间:2011-08-30 04:33:39

标签: iphone core-data

在检查由下面的代码产生的sqlite数据库时,我发现Core Data似乎没有按照创建它们的顺序保存对象(记录)。

-(void) CreateData
{
// Create an organization

NSManagedObjectContext *context = [self managedObjectContext];
NSEntityDescription *org_entity = [NSEntityDescription entityForName:@"Organization" inManagedObjectContext:context];
NSManagedObject *organization = [NSEntityDescription insertNewObjectForEntityForName:[org_entity name] inManagedObjectContext:context];

[organization setValue:@"MyCompany" forKey:@"name"];
[organization setValue:[NSNumber numberWithInt:[organization hash]] forKey:@"id"];


// Create several people

NSEntityDescription *person_entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:context];
NSManagedObject *john = [NSEntityDescription insertNewObjectForEntityForName:[person_entity name] inManagedObjectContext:context];

[john setValue:[NSNumber numberWithInt:[john hash]]  forKey:@"id"];
[john setValue:@"John" forKey:@"name"];


NSManagedObject *jane = [NSEntityDescription insertNewObjectForEntityForName:[person_entity name] inManagedObjectContext:context];

[jane setValue:[NSNumber numberWithInt:[jane hash]]  forKey:@"id"];
[jane setValue:@"Jane" forKey:@"name"];


NSManagedObject *bill = [NSEntityDescription insertNewObjectForEntityForName:[person_entity name] inManagedObjectContext:context];

[bill setValue:[NSNumber numberWithInt:[bill hash]]  forKey:@"id"];
[bill setValue:@"Bill" forKey:@"name"];


// Designate the leader for "My Company"

[organization setValue:john forKey:@"leader"];


// Designate subordinates

NSMutableSet *johns_employees = [john mutableSetValueForKey:@"employee"];
[johns_employees addObject:jane];
[johns_employees addObject:bill];


NSError *error = nil;
if(![context save:&error])
{
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}
}

虽然我不打算依赖实际应用程序的记录顺序,但有趣的是,了解订单似乎是随机的。人们会认为基础序列化例程每次都会产生相同的结果。

出于好奇,为什么会这样?

1 个答案:

答案 0 :(得分:0)

这是一个有趣的句子:

  

'人们会认为基础序列化例程每次都会产生相同的结果'

CoreData抽象出底层存储 - 它可以是plist,xml,sqlite等。你不能假设任何有关底层例程的东西,你不知道它们:)它们是由任何人创建的存储类型决定的要求的NSPersistentStore(你的NSManagedObjectContext连接)。

如果您想按特定顺序取回结果,则需要向NSOrderDescription提供NSFetchRequest;)

PS @ bryanmac的评论对于了解为什么sqlite可能无法以正确的顺序返回结果非常有用。