Coredata usage (simplified)

Source: Internet
Author: User

Coredata usage (simplified)

We have always known only four methods for iOS storage, NSUserDefault and Coredata. The former is self-explanatory. Here we will only summarize the simple usage of Coredata. For beginners.
This article uses a small demo to demonstrate the basic usage of coredata: data storage, addition, deletion, modification, and query.
First, we need to determine the relationship between the two objects.
A family has multiple members, while a member only belongs to one family.
1. Create a project and check the Use Core Data option.

2. In the. xcdatamodel file, create two entities: Family and Member.

3. Establish the relationship between two entities. Type represents the relationship between the two entities. To assign indicates that a family can correspond To multiple Member objects, and the members attribute is the set of these Member objects;

There is also an important point here: Delete Rule, among the four options of DeleteRule:
Deny can reject deletion requests.
Nullify resets the inverse relationship before deleting an object. After the object family is deleted, its member still exists independently in the database, but the family corresponding to member in the database is null.
Cascade deletes an object and all its relationships (Cascade deletion). When a family object is deleted, all its associated member objects are also deleted.
No Action will ensure that the objects to which a link points are not affected, even if these objects point to the items to be deleted

4. By default, all objects retrieved using Core Data are of the NSManagedObject type and can be accessed using key-value pairs. However, in general, when an object accesses data, it sometimes needs to add some business methods to complete some other tasks, so it is necessary to create a subclass of NSManagedObject,




5. In database processing, addition, deletion, modification, and query of Basic Object operations are undisputed foundations:

+ (Void) addNewFamilyWithName :( NSString *) name address :( NSString *) address success :( void (^) () success failure :( void (^) (NSError * error )) failure {AppDelegate * appDelegate = [UIApplication sharedApplication]. delegate; NSManagedObjectContext * context = appDelegate. managedObjectContext; NSManagedObject * family = [NSEntityDescription insertNewObjectForEntityForName: @ "Family" inManagedObjectContext: context ]; [Family setValue: name forKey: @ "name"]; [family setValue: address forKey: @ "address"]; NSError * error = nil; BOOL isSuccess = [context save: & error]; if (! IsSuccess) {if (failure) {failure (error) ;}} else {if (success) {success () ;}}+ (void) deleteFamily :( Family *) family success :( void (^) () success failure :( void (^) (NSError * error) failure {AppDelegate * appDelegate = [UIApplication sharedApplication]. delegate; NSManagedObjectContext * context = appDelegate. managedObjectContext; [context deleteObject: family]; NSError * error = nil; BOOL isSuccess = [c Ontext save: & error]; if (! IsSuccess) {if (failure) {failure (error) ;}} else {if (success) {success () ;}}+ (NSArray *) fetchFamilyLists {AppDelegate * appDelegate = [UIApplication sharedApplication]. delegate; NSManagedObjectContext * context = appDelegate. managedObjectContext; // initialize a query request NSFetchRequest * request = [[NSFetchRequest alloc] init]; // set the object request to be queried. entity = [NSEntityDescription entityForName: @ "Family" inManagedObjectContext: context]; // set the order (by age in descending order) // NSSortDescriptor * sort = [NSSortDescriptor sortDescriptorWithKey: @ "age" ascending: NO]; // request. sortDescriptors = [NSArray arrayWithObject: sort]; // you can specify a condition to filter records whose name contains the string "M". Note: When filtering conditions, % in the Database SQL statement should be replaced by *, so % M % should be written as * M *. For more filtering methods, see the next article) // NSPredicate * predicate = [NSPredicate predicateWithFormat: @ "name like % @", @ "* M *"]; // request. predicate = predicate; // execution request NSError * error = nil; NSArray * objs = [context executeFetchRequest: request error: & error]; if (error) {[NSException raise: @ "query error" format: @ "% @", [error localizedDescription];} // traverse data for (NSManagedObject * obj in objs) {NSLog (@ "name = % @", [obj valueForKey: @ "name"]);} return objs ;}


 

Related Article

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.