在xcode 4.2.1中通过RHManagedObject 和RHManagedObjectContextManager 来简化 CoreData的处理

来源:互联网 发布:电子密码锁编程 编辑:程序博客网 时间:2024/06/05 23:01
项目源码下载 : 在我的资源里面。
  1. RHManagedObjectContextManager 和 RHManagedObject 来自与 https://github.com/chriscdn/RHManagedObject
  2. 在项目中加入 CoreData.framework的框架
  3. 在项目中 加入 RHManagedObjectContextManager.h 和 RHManagedObjectContextManager.m ,RHManagedObject.h ,RHManagedObject.m 4个文件。
  4. 通过 xcode 4.2 新建一个文件,文件类型是 CoreData 下的Data Model 。命名为 test.xcdatamodeld
  5. 然后点击 这个 test.xcdatamodeld 文件,在主视图里面 加入一个 Entity ,名字 叫 :Customer。增加2个 Attribute :1 : name ,2  age
  6. 点击其他文件,取消选中这个 test.xcdatamodeld 文件
  7. 新建一个文件,类型是CoreData下的NSManagedObject subclass
  8. 然后界面上会显示 Data Model的名称,这里显示 test。选中这个test,点击next按钮 ,出现这个 test.xcdatamodeld  文件中定义的Entities ,这里显示 Customer.选中这个Customer ,点击next 按钮。然后在选择保存文档的目录。按按钮 create。这样在项目中就会建立 Customer.h 和 Customer.m文件。
  9. 修改 Customer.h文件
    1.  #import "RHManagedObject.h"
    2. 把原来的基类由 NSManagedObject 修改 为 RHManagedObject.     @interface Customer : RHManagedObject
  10. 修改RHManagedObjectContextManager.h,这只 2个 define值
    1. #define kDatabaseName @"test.sqlite"
      #define kModelName @"test"
    2. kDatabaseName指定的是sqlite数据库的名称,可以任意命名,生成后文件保存在Documents目录下
      kModelName指的是数据模型的名称,必须和在项目中创建的.xcdatamodeld文件的文件名前缀名称一致.

  11. 修改 Customer.m 的源码 ,加入以下代码:
    +(NSString *)entityName {    return @"Customer";}

    // This returns the name of your xcdatamodeld model, without the extension

    +(NSString *)modelName {

        return @"test"; // 这里要放入xcdatamodeld文件名。不需要后缀

    }

  12. 编写数据库 访问功能
 
   //****************** 数据保存 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]];  }


官网的例子:

Examples

Once you have setup RHManagedObject it becomes easier to do common tasks. Here are some examples.

Add a new employee

Employee *employee = [Employee newEntity];[employee setFirstName:@"John"];[employee setLastName:@"Doe"];

Fetch all employees

NSArray *allEmployees = [Employee fetchAll];

Fetch all employees with first name "John"

NSArray *employees = [Employee fetchWithPredicate:[NSPredicate predicateWithFormat:@"firstName=%@", @"John"]];

Fetch all employees with first name "John" sorted by last name

NSArray *employees = [Employee fetchWithPredicate:[NSPredicate predicateWithFormat:@"firstName=%@", @"John"] sortDescriptor:[NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES]];

Get a specific employee record

The +getWithPredicate: method will return the first object if more than one is found.

Employee *employee = [Employee getWithPredicate:[NSPredicate predicateWithFormat:@"employeeID=%i", 12345]];

Count the total number of employees

NSUInteger employeeCount = [Employee count];

Count the total number of employees with first name "John"

NSUInteger employeeCount = [Employee countWithPredicate:[NSPredicate predicateWithFormat:@"firstName=%@", @"John"]];

Get all the unique first names

NSArray *uniqueFirstNames = [Employee distinctValuesWithAttribute:@"firstName" withPredicate:nil];

Get the average age of all employees

NSNumber *averageAge = [Employee aggregateWithType:RHAggregateAverage key:@"age" predicate:nil defaultValue:nil];

Fire all employees

[Employee deleteAll];

Fire a single employee

Employee *employee = [Employee get ...];[employee delete];

Commit changes

This must be called in the same thread where the changes to your objects were made.

[Employee commit];

Completely destroy the Employee model (i.e., delete the .sqlite file)

This is useful to reset your Core Data store after making changes to your model.

[Employee deleteStore];

Get an object instance in another thread

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];});