问题
I am developing an application that uses CoreData.
So in .sqlite file, It manages Primary key itself.
Primary key attribute name is Z_PK.
My problem is that, I wants data from my table sorted ascending by primary key.
I'm using that code
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"_PK" ascending:YES];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
[sort release];
But it's not working.
when I'm using "title" insted of "_PK", It's working Fine
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
[sort release];
So is there any different way to use Table's Primary key?
回答1:
CoreData manages persistent object graphs. It is not a RDBM. You have no control over the unique primary key, so you have no control over its value. It is merely an implementation detail, and should not be referenced for any reason.
Thus, why do you want to sort based on it? I can think of several reasons...
- You want to access the objects in the order in which they were added to the database. However, you can easily do this in several ways.
1a. You can add a field to each Entity. You can set it to be a UUID, or in increasing integer.
1b. You could have an entity, something like "EntityList" which has an ordered one-to-many relationship to "Entity."
1c. You could add a one-to-one relationship from Entity to itself, then just manage it like a linked list. Every time you add an Entity, put it at the end of the list.
Either of this solutions give you the ability to access the Entity objects in order they were added.
- Or, you really don't care the order you see them, but you want a consistent ordering.
2a. Add a primaryKey attribute, and assign it a UUID.
2b. Use the ordered to-many relationship.
Finally, if you really want primary-key-based access, I would suggest having a separate sqlite database that you use for special keyed access. You can then associate a key to the objectID of an object in the CoreData store.
来源:https://stackoverflow.com/questions/10153335/iphone-core-data-fetch-primary-key