开发者

NSSortDescriptor for NSFetchRequest sorting unexpectedly

开发者 https://www.devze.com 2023-01-01 01:27 出处:网络
My entity has a property (sortOrder) that is of the type Decimal(NSDecimalNumber) but when I execute a fetch request using that property as a key, I get back results in a seemingly random order.If I o

My entity has a property (sortOrder) that is of the type Decimal(NSDecimalNumber) but when I execute a fetch request using that property as a key, I get back results in a seemingly random order. If I output the value of the property I get really strange values until I get it's intValue.

Example: The first run produces this result. The first value is the raw value of the property. The second is the intValue, the actual value of the property when I created the object - or at least I thought.

85438160 10

74691424 20

Second run...

85333744 10

85339168 20

Third...

85263696 20

85269568 10

What the hell?

Fetch Request:

NSMutableArray *cats = [[NSMutableArray alloc] initWithArray:[CoreDataHelper searchObjectsInContext:@"RestaurantMenuCategory":nil:@"sortOrder":YES:NO:nil]];

Here is the searchObjectsInContext method from my CoreDataHelperCl开发者_Go百科ass:

+(NSMutableArray *) searchObjectsInContext: (NSString*)entityName : (NSPredicate *)predicate : (NSString*)sortKey : (BOOL)sortAscending : (BOOL)distinct : (NSString*)distinctProperty
{
    RestaurantController *ctrl = [RestaurantController sharedRestaurantController];

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:ctrl.managedObjectContext];
    [request setEntity:entity];

    if(distinct==YES){
        [request setReturnsDistinctResults:YES];
    }

    if(distinctProperty!= nil){
        [request setPropertiesToFetch :[NSArray arrayWithObjects:distinctProperty,nil]];
    }

    if(predicate != nil){
        [request setPredicate:predicate];
    }

    if(sortKey != nil){
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:sortAscending];
        NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
       [request setSortDescriptors:sortDescriptors];
       [sortDescriptors release];
       [sortDescriptor release];
   }

   NSError *error;

   NSMutableArray *mutableFetchResults = [[[ctrl.managedObjectContext executeFetchRequest:request error:&error] mutableCopy] autorelease];

   [request release];

   return mutableFetchResults;
}


You cannot use a %d format to print out an NSDecimalNumber.

NSDecimalNumber is an Objective-C object; %d is for printing "int"s. If you use the %d format string, it will probably print something non-useful like the address of the object; use "%@" instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消