iOS Get objects from CoreData sorted by primary key

扶醉桌前 提交于 2019-12-02 00:17:32

Anything not exposed to you by the Core Data framework is an implementation detail. The fact that Z_PK exists, and currently suits your purposes, cannot be relied upon.

If creation/save order is important to your model, then it should be included in your model. There's really nothing else to it.

There is no proper method in core data framework to sort object by primary key, but I think we can use objectID as a the primary key and sort by objectID. ObjectID for a particular object would always increase.. thus you can use below method

/*!
@param <NSManagedObject> array 
@return <NSManagedObject> sortedarray
*/

+ (NSArray *) sortManagedObjectArrayByObjectID:(NSArray *) array {

    NSArray *compareResult = [array sortedArrayUsingComparator:^NSComparisonResult(NSManagedObject *obj1, NSManagedObject *obj2) {

        NSString *s = [obj1.objectID.URIRepresentation lastPathComponent];
        NSString *r = [obj2.objectID.URIRepresentation lastPathComponent];
        return [s compare:r];

    }];

    return compareResult;

}

Hope this would help

Use a sort descriptor with self as the sort key. The underlying SQL will have ORDER BY t0.Z_PK.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!