Open Source Library Magicalrecord operation CoreData

Source: Internet
Author: User
Tags ruby on rails

Original:http://www.cnblogs.com/YouXianMing/p/3597808.html

Magicalrecord Https://github.com/magicalpanda/MagicalRecord

Note: Magicalrecord operates under ARC, core data is an ORM scheme, it is said to bring more trouble than benefits, and core data created by the table does not have a primary key, but for the database has no performance requirements, simple data operation is fully sufficient, can simplify the countless code volume.

Magicalrecord

In software engineering, the active record pattern was a design pattern found in software that stores it data in Relationa L databases. It was named by Martin Fowler in his book Patterns of Enterprise application Architecture. The interface to such a object would include functions such as Insert, Update, and Delete, plus properties that correspon D more-or-less directly to the columns in the underlying database table.

In software engineering, the real-time mapping of object and database is a design pattern, which appears in software of relational database. This design pattern is recorded in Martin Fowler's <patterns of Enterprise application Architecture>. The interface of the object being manipulated should include the method of adding and removing, and the basic attribute is not much more than the database of a record corresponding.

The Active record is an approach to accessing data in a database. A database table or view is wrapped into a class; Thus an object instance was tied to a single row in the table. After creation of a object, a new row was added to the table upon save. Any object loaded gets the IT information from the database; When a object is updated, the corresponding row in the table is also updated. The wrapper class implements accessor methods or properties for each column in the table or view.

A real-time mapping record is a way of manipulating a database in which a table is encapsulated as an object, and an instance of that object corresponds to a record in that table. When an object is created, a record is inserted into the table and saved. The property information in any loaded object is read from the database; When an object is updated, the corresponding record in the database table is also updated. This encapsulated class implements the method of real-time operation, and its property one by one corresponds to the properties of the table in the database.

-Wikipedia

Magicalrecord was inspired by the ease of Ruby on Rails ' Active Record fetching. The goals of this code is:

    • Clean up my Core Data related code
    • Allow for clear, simple, one-line fetches
    • Still allow the modification of the nsfetchrequest when request optimizations is needed

Magicalrecord is inspired by the simple Ruby language of the Rails ' Active Record Query method. Magicalrecord The core idea of this open source library is:

    • Clear Core Data-related code
    • Clean, simple line search record function
    • Of course, Nsfetchrequest is allowed, when complex search conditions exist.

Don't be offended by the poor translation, here is my tutorial on using the latest Xcode 5.1 open ARC environment.

1. Drag the Magicalrecord folder into the project file to introduce the Coredata.frame framework

2. Introduce the header file in the. pch file Coredata+magicalrecord.h

Note: The header file can only be in a. pch file, otherwise it cannot be compiled

3. Create a Model.xcdatamodeld file and create a Student entities, and finally create the Student class

4. Write the following code in the APPDELETE.M file

The following is the basic operation of adding and removing changes, but note that before doing any database operations, please initialize the following, in the AppDelete load-time initialization once, or can not find the database and crashes, you understand.

Set database name
[Magicalrecord setupcoredatastackwithstorenamed:@ "Model.sqlite"];

Increase

Add a record
Student *person = [Student mr_createentity];
Person.name = @ "y.x.";
[[Nsmanagedobjectcontext Mr_defaultcontext] mr_savetopersistentstoreandwait];

Note: After you create an object, you need to perform a storage operation

Inquire

Querying all the records

Nsarray *students = [Student Mr_findall];


A condition query based on a property

Nsarray *students = [Student mr_findbyattribute:@ "name" withvalue:@ "y.x."];

Get search Results by sort

Nsarray *students = [Student mr_findallsortedby:@ "name" Ascending:yes];

I don't list them all, just look at the header file and I'll know.

Querying All records

+ (Nsarray *) Mr_findall;

Querying all records based on context handles
+ (Nsarray *) Mr_findallincontext: (Nsmanagedobjectcontext *) context;

Sort all records by an attribute
+ (Nsarray *) Mr_findallsortedby: (NSString *) Sortterm Ascending: (BOOL) ascending;

Query all records based on a property sort and context action handle
+ (Nsarray *) Mr_findallsortedby: (NSString *) Sortterm Ascending: (BOOL) Ascending incontext: (Nsmanagedobjectcontext *) Context

Sort by a property to query a record with a predicate
+ (Nsarray *) Mr_findallsortedby: (NSString *) Sortterm Ascending: (BOOL) Ascending withpredicate: (Nspredicate *) Searchterm;

Querying records based on a property sort and context manipulation handle with predicates
+ (Nsarray *) Mr_findallsortedby: (NSString *) Sortterm Ascending: (BOOL) Ascending withpredicate: (Nspredicate *) Searchterm incontext: (Nsmanagedobjectcontext *) context;

Query by predicate
+ (Nsarray *) Mr_findallwithpredicate: (Nspredicate *) searchterm;

Query based on predicates and context manipulation handles
+ (Nsarray *) Mr_findallwithpredicate: (Nspredicate *) searchterm incontext: (Nsmanagedobjectcontext *) context;

The following is the operation of querying an object, repeat with above, not repeating
+ (instancetype) Mr_findfirst;
+ (Instancetype) Mr_findfirstincontext: (Nsmanagedobjectcontext *) context;
+ (Instancetype) mr_findfirstwithpredicate: (Nspredicate *) searchterm;
+ (Instancetype) mr_findfirstwithpredicate: (Nspredicate *) searchterm incontext: (Nsmanagedobjectcontext *) context;
+ (Instancetype) mr_findfirstwithpredicate: (Nspredicate *) searchterm sortedby: (NSString *) Property Ascending: (BOOL) ascending;
+ (Instancetype) mr_findfirstwithpredicate: (Nspredicate *) searchterm sortedby: (NSString *) Property Ascending: (BOOL) Ascending Incontext: (Nsmanagedobjectcontext *) context;
+ (Instancetype) mr_findfirstwithpredicate: (Nspredicate *) searchterm andretrieveattributes: (NSArray *) attributes;
+ (Instancetype) mr_findfirstwithpredicate: (Nspredicate *) searchterm andretrieveattributes: (NSArray *) attributes Incontext: (Nsmanagedobjectcontext *) context;
+ (Instancetype) mr_findfirstwithpredicate: (Nspredicate *) searchterm sortedby: (NSString *) SortBy Ascending: (BOOL) Ascending andretrieveattributes: (id) attributes, ...;
+ (Instancetype) mr_findfirstwithpredicate: (Nspredicate *) searchterm sortedby: (NSString *) SortBy Ascending: (BOOL) Ascending Incontext: (Nsmanagedobjectcontext *) context andretrieveattributes: (ID) attributes, ...;
+ (Instancetype) Mr_findfirstbyattribute: (NSString *) attribute Withvalue: (id) searchvalue;
+ (Instancetype) Mr_findfirstbyattribute: (NSString *) attribute Withvalue: (ID) searchvalue Incontext: ( Nsmanagedobjectcontext *) Context;
+ (Instancetype) Mr_findfirstorderedbyattribute: (NSString *) attribute ascending: (BOOL) ascending;
+ (Instancetype) Mr_findfirstorderedbyattribute: (NSString *) attribute ascending: (BOOL) Ascending incontext: ( Nsmanagedobjectcontext *) Context;

Modify

Nsarray *students = [Student mr_findbyattribute:@ "name" withvalue:@ "y.x."];
For (Student *tmp in students) {
Tmp.name = @ "Jane";
}
[[Nsmanagedobjectcontext Mr_defaultcontext] mr_savetopersistentstoreandwait];

Note: Since you need to modify the records first, find the records according to the criteria, then modify and then save

Delete

Nsarray *students = [Student mr_findbyattribute:@ "name" withvalue:@ "Frank"];
For (Student *tmp in students) {
[TMP mr_deleteentity];
}
[[Nsmanagedobjectcontext Mr_defaultcontext] mr_savetopersistentstoreandwait];

Note: Since you want to delete first you need to find the record, match the criteria to find the record, then delete, and then save

Experience

If there is no performance requirement for the operational database in your project, use the CoreData-related open Source Library.

CoreData operation is more complex, Magicalrecord has a lot of features, such as can be set in the main thread or sub-thread operation, convenient and fast, can enter the best 10 big open Source Library has its own unique place, will use Magicalrecord need to have a certain CoreData related knowledge, I also just now learn to use, but know that it can bring benefits for development, using the database of friends have the following choices.

1. SQLite3 C function form (I have done a dry embedded development before, even if it is not recommended to use a process-oriented concept of SQLite3, there is a better way why not?)

2. FMDB to the SQLite3 package, with the concept of objects, familiar with the sq statement of friends can use, but have not done the object and record real-time correspondence

3. CoreData He does the real-time correspondence between objects and records, using its own search system (not sq language), but its basic operation and configuration is daunting.

4. Magicalrecord to coredata the official use of the human packaging, used CoreData basic operation and then use Magicalrecord will have a deep experience

5. Objectiverecord is also a humane package for CoreData, using more fools, but the price of a fool is to sacrifice some more powerful features, search for keywords on github

Appendix:

1. The default is stored in the background, does not block the main thread

I have defined macro Mr_shorthand in the Coredata+magicalrecord.h file, so I don't need mr_ prefix in the method.

The following is code (provides block to notify storage success, asynchronous operation)

The following is the printing information

--------------------------------------------------------------------------------------------------------------- -------------------------------------

2014-03-13 11:17:43.616 studymagicalrecord[26416:60b] +[nsmanagedobjectcontext (Magicalrecord) MR_ Contextwithstorecoordinator:] (0x2f4498), Created Context UNNAMED
2014-03-13 11:17:43.616 studymagicalrecord[26416:60b] +[nsmanagedobjectcontext (Magicalrecord) MR_ Setrootsavingcontext:] (0x2f4498) Set Root saving Context: <NSManagedObjectContext:0xe74d910>
2014-03-13 11:17:43.617 studymagicalrecord[26416:60b] +[nsmanagedobjectcontext (Magicalrecord) MR_ Newmainqueuecontext] (0x2f4498) Created Main Queue Context: <NSManagedObjectContext:0xe74e040>
2014-03-13 11:17:43.617 studymagicalrecord[26416:60b] +[nsmanagedobjectcontext (Magicalrecord) MR_setDefaultContext :] (0x2f4498) Set Default Context: <NSManagedObjectContext:0xe74e040>
2014-03-13 11:17:43.618 studymagicalrecord[26416:60b]-[nsmanagedobjectcontext (magicalsaves) MR_saveWithOptions: Completion:] (0xe74e040) →saving <nsmanagedobjectcontext (0xe74e040): * * * DEFAULT ***> on * * * MAIN THREAD * * *
2014-03-13 11:17:43.618 studymagicalrecord[26416:60b]-[nsmanagedobjectcontext (magicalsaves) MR_saveWithOptions: Completion:] (0xe74e040) →save parents? 1
2014-03-13 11:17:43.619 studymagicalrecord[26416:60b]-[nsmanagedobjectcontext (magicalsaves) MR_saveWithOptions: Completion:] (0xe74e040) →save synchronously? 0
2014-03-13 11:17:43.619 studymagicalrecord[26416:60b] time
2014-03-13 11:17:43.622 studymagicalrecord[26416:60b]-[nsmanagedobjectcontext (Magicalrecord) MR_contextWillSave:] (0xe74e040) Context DEFAULT is on to save. Obtaining permanent IDs for new 1 inserted objects
2014-03-13 11:17:43.623 studymagicalrecord[26416:60b]-[nsmanagedobjectcontext (magicalsaves) MR_saveWithOptions: Completion:] (0xe74d910) →saving <nsmanagedobjectcontext (0xe74d910): * * * BACKGROUND saving (ROOT) ***> on * * * MAIN THREAD * * *
2014-03-13 11:17:43.624 studymagicalrecord[26416:60b]-[nsmanagedobjectcontext (magicalsaves) MR_saveWithOptions: Completion:] (0xe74d910) →save parents? 1
2014-03-13 11:17:43.624 studymagicalrecord[26416:60b]-[nsmanagedobjectcontext (magicalsaves) MR_saveWithOptions: Completion:] (0xe74d910) →save synchronously? 0
2014-03-13 11:17:43.625 studymagicalrecord[26416:1303]-[nsmanagedobjectcontext (MagicalRecord) MR_contextWillSave: ] (0xe74d910) Context BACKGROUND Saving (ROOT) is about to save. Obtaining permanent IDs for new 1 inserted objects
2014-03-13 11:17:43.626 studymagicalrecord[26416:1303] __70-[nsmanagedobjectcontext (MagicalSaves) MR_ Savewithoptions:completion:]_block_invoke25 (0xe74d910) →finished saving: <nsmanagedobjectcontext (0xe74d910): * * * BACKGROUND Saving (ROOT) ***> on * * * BACKGROUND THREAD * * *
2014-03-13 11:17:43.627 studymagicalrecord[26416:60b] YES

--------------------------------------------------------------------------------------------------------------- -------------------------------------

2. How do I turn off the print information provided by Magicalrecord?

Modify the value at line 23 of MagicalRecord.h and change 0 to 1.

Open Source Library Magicalrecord operation CoreData

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.