我在ios应用中使用了核心数据。现在我有一个表,其中有两列。
分类
订单(其中有NSNumber 1,2,5)
我想获取数据,因此它将首先按类别名称而不是按订单号按字母顺序排序。
我使用了以下代码:
NSEntityDescription *entity_Maintness = [NSEntityDescription
entityForName:@"Maintness" inManagedObjectContext:__managedObjectContext];
[fetchRequest_Maintness setEntity:entity_Maintness];
NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"type" ascending:YES];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"serialNumber" ascending:NO];
NSArray *sortDescriptors12 = [[NSArray alloc] initWithObjects:sortDescriptor1, sortDescriptor, nil];
[fetchRequest_Maintness setSortDescriptors:sortDescriptors12];
但数据仅按类别而不是按序列号排序。
感谢您的帮助。
答案 0 :(得分:1)
上面的代码看起来不错。也许你的代码中有其他问题?以下是我为您快速生成的一些代码,可以作为起点?
#import "MainViewController.h"
#import "Maintness.h"
@interface MainViewController ()
@property (weak, nonatomic) IBOutlet UITextField *type;
@property (weak, nonatomic) IBOutlet UITextField *serialNumber;
@property (strong, nonatomic) NSManagedObjectContext *context;
- (IBAction)addButtonPressed:(id)sender;
- (IBAction)retrieveButtonPressed:(id)sender;
@end
@implementation MainViewController
#pragma mark - lazy instantiation
- (NSManagedObjectContext *)context{
if (!_context){
id appDelegate = (id)[[UIApplication sharedApplication] delegate];
_context = [appDelegate managedObjectContext];
}
return _context;
}
#pragma mark - core data interactions
- (IBAction)addButtonPressed:(id)sender {
NSError *error = nil;
Maintness *newMaintness = nil;
newMaintness = [NSEntityDescription insertNewObjectForEntityForName:@"Maintness" inManagedObjectContext:self.context];
newMaintness.type = self.type.text;
newMaintness.serialNumber = self.serialNumber.text;
if (![self.context save:&error]) {
NSLog(@"Oh no - error: %@", [error localizedDescription]);
} else {
NSLog(@"It appears the details were added ok");
}
}
- (IBAction)retrieveButtonPressed:(id)sender {
NSError *error = nil;
// Set up fetch
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
// Set up entity
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Maintness" inManagedObjectContext:self.context];
[fetch setEntity:entity];
// Set up sorting
// - sorts in order of array
NSSortDescriptor *primarySortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"type" ascending:YES];
NSSortDescriptor *secondarySortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"serialNumber" ascending:NO];
NSArray *sortDescriptors = @[primarySortDescriptor, secondarySortDescriptor];
[fetch setSortDescriptors:sortDescriptors];
NSArray *results = [self.context executeFetchRequest:fetch error:&error];
for (Maintness *result in results) {
NSLog(@"type: %@ serial number: %@", result.type, result.serialNumber);
}
}
@end