+(NSString *)entityName { return @"Customer"; }// This returns the name of your xcdatamodeld model, without the extension
+(NSString *)modelName {
return @"test"; // 这里要放入xcdatamodeld文件名。不需要后缀
}
//****************** 数据保存 begin Customer * customer = (Customer *) [Customer newEntity]; customer.name =@"asdfsf"; customer.age = [[ NSNumber alloc] initWithFloat: 13.4f]; [RHManagedObject commit]; //****************** 数据保存 end
-(NSArray * ) allRecords { NSLog(@"获取所有记录"); //NSPredicate *predicate = [NSPredicate predicateWithFormat:@"1=1"]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"smount" ascending:YES]; return [[NSArray alloc] initWithArray:[CustomerInfo fetchWithSortDescriptor:sortDescriptor]]; }
官网的例子:
Once you have setup RHManagedObject it becomes easier to do common tasks. Here are some examples.
Employee *employee = [Employee newEntity];
[employee setFirstName:@"John"];
[employee setLastName:@"Doe"];
NSArray *allEmployees = [Employee fetchAll];
NSArray *employees = [Employee fetchWithPredicate:[NSPredicate predicateWithFormat:@"firstName=%@", @"John"]];
NSArray *employees = [Employee fetchWithPredicate:[NSPredicate predicateWithFormat:@"firstName=%@", @"John"] sortDescriptor:[NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES]];
The +getWithPredicate:
method will return the first object if more than one is found.
Employee *employee = [Employee getWithPredicate:[NSPredicate predicateWithFormat:@"employeeID=%i", 12345]];
NSUInteger employeeCount = [Employee count];
NSUInteger employeeCount = [Employee countWithPredicate:[NSPredicate predicateWithFormat:@"firstName=%@", @"John"]];
NSArray *uniqueFirstNames = [Employee distinctValuesWithAttribute:@"firstName" withPredicate:nil];
NSNumber *averageAge = [Employee aggregateWithType:RHAggregateAverage key:@"age" predicate:nil defaultValue:nil];
[Employee deleteAll];
Employee *employee = [Employee get ...];
[employee delete];
This must be called in the same thread where the changes to your objects were made.
[Employee commit];
This is useful to reset your Core Data store after making changes to your model.
[Employee deleteStore];
Core Data doesn't allow managed objects to be passed between threads. However you can generate a new object in a separate thread that's valid for that thread. Here's an example using the -objectInCurrentThreadContext
method:
Employee *employee = [Employee getWithPredicate:[NSPredicate predicateWithFormat:@"employeID=%i", 12345]];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// employee is not valid in this thread, so we fetch one that is:
Employee *employee2 = [employee objectInCurrentThreadContext];
// do something with employee2
[Employee commit];
});