AppDelegate *appDelegate =
[[UIApplicationsharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
//classes
NSEntityDescription *entityDescriptionForClass = [NSEntityDescription
entityForName:@"ClassEntity"
inManagedObjectContext:context];
NSFetchRequest *requestForClass = [[NSFetchRequestalloc] init];
[requestForClass setEntity:entityDescriptionForClass];
NSError *error;
NSArray *objectsForClass = [context executeFetchRequest:requestForClass error:&error];
if (objectsForClass == nil) {
NSLog(@"There was an error in my Zander App!");
// Do whatever error handling is appropriate 可以在这里填写 当发生存取错误的时候 处理的内容
}
//初始化一个entity对象
StudentEntity *student1= [[StudentEntity alloc]initWithEntity:entityDescription insertIntoManagedObjectContext:context];
student1.name = @"student1_1";
student1.student_class = class1;
//将set 转化成 可变数组mutablearray
NSSet *set = selectedClass.class_student;
NSSortDescriptor *sort = [NSSortDescriptorsortDescriptorWithKey:@"index"ascending:YES];
NSArray *array = [set sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];
NSMutableArray *studentsArray = [NSMutableArrayarrayWithArray:array] ;
//降序取数据的 NSFetchRequest 声明
NSFetchRequest *fetchRequest2 =[[NSFetchRequestalloc]init];
NSEntityDescription *entity = [NSEntityDescriptionentityForName:@"EntityName" inManagedObjectContext:context];
[fetchRequest2 setEntity:entity];
[fetchRequest2 setSortDescriptors:[NSArrayarrayWithObject:[NSSortDescriptorsortDescriptorWithKey:@"displayOrder"ascending:NO]]];
主要用的就是这个 [fetchRequest2 setSortDescriptors:[NSArrayarrayWithObject:[NSSortDescriptorsortDescriptorWithKey:@"displayOrder"ascending:NO]]];
设置这个数据库取数据的请求 1. 按照那个字段 (displayOrder) 2. 排序:升序还是降序 YES (升序) NO(降序)