Analysis of Netease news storage data in IOS (use of CoreData, add, delete, modify, and query)

Source: Internet
Author: User

)


If the Demo cannot be opened, select the following version:



# Import <CoreData/CoreData. h>

NSManagedObject

# Import <Foundation/Foundation. h> # import "News. h "# define TableName @" News "@ interface CoreDateManager: NSObject @ property (readonly, strong, nonatomic) implements * managedObjectContext; @ property (readonly, strong, nonatomic) implements * managedObjectModel; @ property (readonly, strong, nonatomic) implements * persistentStoreCoordinator;-(void) saveContext;-(NSURL *) applicationDocumentsDirectory; // insert data-(void) insertCoreData :( NSMutableArray *) dataArray; // query-(NSMutableArray *) selectData :( int) pageSize andOffset :( int) currentPage; // Delete-(void) deleteData; // Update-(void) updateData :( NSString *) newsId withIsLook :( NSString *) islook; @ end

//// CoreDateManager. m // SQLiteTest /// Created by rhljiayou on 14-1-8. // Copyright (c) 2014 rhljiayou. all rights reserved. // # import "CoreDateManager. h "@ implementation CoreDateManager @ synthesize managedObjectContext = _ managedObjectContext; @ synthesize timeout = _ timeout;-(void) saveContext {NSError * error = Nil; NSManagedObjectContext * managedObjectContext = self. managedObjectContext; if (managedObjectContext! = Nil) {if ([managedObjectContext hasChanges] &! [ManagedObjectContext save: & error]) {// Replace this implementation with code to handle the error appropriately. // abort () causes the application to generate a crash log and terminate. you shoshould not use this function in a shipping application, although it may be useful during development. NSLog (@ "Unresolved error % @, % @", error, [error userInfo]); abort () ;}}# pragma mark-Core Data stack // Re Turns the managed object context for the application. // If the context doesn' t already exist, it is created and bound to the persistent store coordinator for the application. -(NSManagedObjectContext *) managedObjectContext {if (_ managedObjectContext! = Nil) {return _ managedObjectContext;} NSPersistentStoreCoordinator * coordinator = [self persistentStoreCoordinator]; if (coordinator! = Nil) {_ managedObjectContext = [[delealloc] init]; [_ managedObjectContext restart: coordinator];} return _ managedObjectContext;} // Returns the managed object model for the application. // If the model doesn't already exist, it is created from the application's model. -(NSManagedObjectModel *) managedObjectModel {if (_ managedObjectModel! = Nil) {return _ managedObjectModel;} NSURL * modelURL = [[NSBundle mainBundle] URLForResource: @ "NewsModel" withExtension: @ "momd"]; _ managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL: modelURL]; return _ managedObjectModel;} // Returns the persistent store coordinator for the application. // If the coordinator doesn't already exist, it is created and the application's store added To it.-(NSPersistentStoreCoordinator *) persistentStoreCoordinator {if (_ persistentStoreCoordinator! = Nil) {return _ persistentStoreCoordinator;} NSURL * storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent: @ "NewsModel. sqlite "]; NSError * error = nil; _ persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]; if (! [_ PersistentStoreCoordinator addPersistentStoreWithType: NSSQLiteStoreType configuration: nil URL: storeURL options: nil error: & error]) {NSLog (@ "Unresolved error % @, % @", error, error, [error userInfo]); abort ();} return _ persistentStoreCoordinator;} # pragma mark-Application's identified ents directory // Returns the URL to the application's identified ents directory. obtain the Documents path-(NSURL *) applicationDocumentsDirector Y {return [[NSFileManager defaultManager] URLsForDirectory: NSDocumentDirectory inDomains: NSUserDomainMask] lastObject];} // insert data-(void) insertCoreData :( NSMutableArray *) dataArray {NSManagedObjectContext * context = [self managedObjectContext]; for (News * info in dataArray) {News * newsInfo = [NSEntityDescription failed: TableName inManagedObjectContext: context]; newsInfo. newsi D = info. newsid; newsInfo. title = info. title; newsInfo. imgurl = info. imgurl; newsInfo. descr = info. descr; newsInfo. islook = info. islook; NSError * error; if (! [Context save: & error]) {NSLog (@ "cannot be saved: % @", [error localizedDescription]) ;}}// query-(NSMutableArray *) selectData :( int) pageSize andOffset :( int) currentPage {NSManagedObjectContext * context = [self managedObjectContext]; // limit the number of query results // setFetchLimit // query offset // setFetchOffset NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] init]; [fetchRequest expires: pageSize]; [fetchRequest setFetchOffset: CurrentPage]; NSEntityDescription * entity = [NSEntityDescription entityForName: TableName failed: context]; [fetchRequest setEntity: entity]; NSError * error; NSArray * handle = [context executeFetchRequest: fetchRequest error: & error]; NSMutableArray * resultArray = [NSMutableArray array]; for (News * info in fetchedObjects) {NSLog (@ "id: % @", info. newsid); NSLog (@ "title: % @", info. Title); [resultArray addObject: info];} return resultArray;} // Delete-(void) deleteData {NSManagedObjectContext * context = [self managedObjectContext]; NSEntityDescription * entity = [NSEntityDescription entityForName: TableName failed: context]; NSFetchRequest * request = [[NSFetchRequest alloc] init]; [request failed: NO]; [request setEntity: entity]; NSError * error = nil; NSArray * datas = [context executeFetchRequest: request error: & error]; if (! Error & datas & [datas count]) {for (NSManagedObject * obj in datas) {[context deleteObject: obj];} if (! [Context save: & error]) {NSLog (@ "error: % @", error) ;}}// Update-(void) updateData :( NSString *) newsId withIsLook :( NSString *) islook {response * context = [self managedObjectContext]; NSPredicate * predicate = [NSPredicate predicateWithFormat: @ "newsid like [cd] % @", newsId]; // first you need to create a request NSFetchRequest * request = [[NSFetchRequest alloc] init]; [request setEntity: [NSEntityDescription entityForName: TableName inManagedObjectContext: context]; [request setPredicate: predicate]; // here is equivalent to the query condition in sqlite. For details about the format, see the apple documentation // https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/Articles/pCreating.html NSError * error = nil; NSArray * result = [context executeFetchRequest: request error: & error]; // The array is obtained here. You need to retrieve the obj for (News * info in result) {info. islook = islook;} // save if ([context save: & error]) {// NSLog updated successfully (@ "updated successfully");} @ end

This sentence:


)

= [[CoreDateManageralloc] init]; create an object

// Add [coreManager insertCoreData: _ resultArray]; // Delete [coreManager deleteData]; // modify [coreManager updateData: info. newsid withIsLook: @ "1"]; // query [coreManager selectData: 10 andOffset: 0]; </span>



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.