iOS Get objects from CoreData sorted by primary key

后端 未结 3 1769
南旧
南旧 2021-01-22 04:29

I have saved data into db using CoreData. I need to fetch data from my table in same order that it was saved. Inside table it is ordered by Z_PK - hidded CoreData key. How can I

相关标签:
3条回答
  • 2021-01-22 04:58

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

    0 讨论(0)
  • 2021-01-22 05:04

    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

    0 讨论(0)
  • 2021-01-22 05:05

    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.

    0 讨论(0)
提交回复
热议问题