IOS之分析網易新聞儲存資料(CoreData的使用,增刪改查)

來源:互聯網
上載者:User


如果Demo打不開請選擇一下版本:



#import<CoreData/CoreData.h>

NSManagedObject

#import <Foundation/Foundation.h>#import "News.h"#define TableName @"News"@interface CoreDateManager : NSObject@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;- (void)saveContext;- (NSURL *)applicationDocumentsDirectory;//插入資料- (void)insertCoreData:(NSMutableArray*)dataArray;//查詢- (NSMutableArray*)selectData:(int)pageSize andOffset:(int)currentPage;//刪除- (void)deleteData;//更新- (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 managedObjectModel = _managedObjectModel;@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;- (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 should 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// Returns 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 = [[NSManagedObjectContext alloc] init];        [_managedObjectContext setPersistentStoreCoordinator: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 userInfo]);        abort();    }        return _persistentStoreCoordinator;}#pragma mark - Application's Documents directory// Returns the URL to the application's Documents directory.擷取Documents路徑- (NSURL *)applicationDocumentsDirectory{    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];}//插入資料- (void)insertCoreData:(NSMutableArray*)dataArray{    NSManagedObjectContext *context = [self managedObjectContext];    for (News *info in dataArray) {        News *newsInfo = [NSEntityDescription insertNewObjectForEntityForName:TableName inManagedObjectContext:context];        newsInfo.newsid = 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(@"不能儲存:%@",[error localizedDescription]);        }    }}//查詢- (NSMutableArray*)selectData:(int)pageSize andOffset:(int)currentPage{    NSManagedObjectContext *context = [self managedObjectContext];        // 限定查詢結果的數量    //setFetchLimit    // 查詢的位移量    //setFetchOffset        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];    [fetchRequest setFetchLimit:pageSize];    [fetchRequest setFetchOffset:currentPage];        NSEntityDescription *entity = [NSEntityDescription entityForName:TableName inManagedObjectContext:context];    [fetchRequest setEntity:entity];    NSError *error;    NSArray *fetchedObjects = [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;}//刪除-(void)deleteData{    NSManagedObjectContext *context = [self managedObjectContext];    NSEntityDescription *entity = [NSEntityDescription entityForName:TableName inManagedObjectContext:context];    NSFetchRequest *request = [[NSFetchRequest alloc] init];    [request setIncludesPropertyValues: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);          }      }}//更新- (void)updateData:(NSString*)newsId  withIsLook:(NSString*)islook{    NSManagedObjectContext *context = [self managedObjectContext];    NSPredicate *predicate = [NSPredicate                              predicateWithFormat:@"newsid like[cd] %@",newsId];        //首先你需要建立一個request    NSFetchRequest * request = [[NSFetchRequest alloc] init];    [request setEntity:[NSEntityDescription entityForName:TableName inManagedObjectContext:context]];    [request setPredicate:predicate];//這裡相當於sqlite中的查詢條件,具體格式參考蘋果文檔        //https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/Articles/pCreating.html    NSError *error = nil;    NSArray *result = [context executeFetchRequest:request error:&error];//這裡擷取到的是一個數組,你需要取出你要更新的那個obj    for (News *info in result) {        info.islook = islook;    }        //儲存    if ([context save:&error]) {        //更新成功        NSLog(@"更新成功");    }}@end

此句:


= [[CoreDateManageralloc]init];建立對象

//增[coreManager insertCoreData:_resultArray];  //刪      [coreManager deleteData];  //改      [coreManager updateData:info.newsid withIsLook:@"1"];  //查      [coreManager selectData:10 andOffset:0];</span> 



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.