Coredata的使用方法(簡)

來源:互聯網
上載者:User

Coredata的使用方法(簡)

一直以來只知道iOS儲存的四種方法,常用的也是NSUserDefault和Coredata。前者使用自不必說。這裡只對Coredata的簡單用法做個小結。供初學者參考。
本文將通過一個小demo,來展示coredata基本的使用:對資料的儲存,和增刪改查等行為。
首先我們要確定兩個對象的關係
一個family家庭有多個成員member,而一個member只屬於一個家庭。
1.我們首先建立一個項目,勾選Use Core Data選項

2.在.xcdatamodel檔案中,建立兩個實體,Family和Member

3.建立兩個實體之間的聯絡,Type代表兩個實體之間的關係,To Many表示一個family可以對應多個Member對象,而members屬性就是這些Member 對象的集合;

這裡還有一個重要的點就是Delete Rule,DeleteRule的四個選項中:
Deny 可以拒絕刪除請求
Nullify 在刪除對象之前重設逆向關係,當刪除對象family之後,他的下屬成員member仍然在資料庫中獨立存在,只是在資料庫中member對應的family為null。
Cascade 刪除對象及它的所有關係(串聯刪除),當刪除一個family對象時,所有與他關聯的member對象也會同時被刪除
No Action 將保證一個關係所指向的對象不受影響,即使這些對象指向了即將被刪除的項

4.預設情況下,利用Core Data取出的實體都是NSManagedObject類型的,能夠利用鍵-值對來存取資料。但是一般情況下,實體在存取資料的基礎上,有時還需要添加一些業務方法來完成一些其他任務,那麼就必須建立NSManagedObject的子類,




5.在資料庫處理中,對象的基本操作增刪改查都是無可爭議的基礎:

+(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 = [context save:&error];    if (!isSuccess) {        if (failure) {            failure(error);        }    }else{        if (success) {            success();        }    }}+(NSArray *)fetchFamilyLists{    AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;    NSManagedObjectContext *context = appDelegate.managedObjectContext;    // 初始化一個查詢請求    NSFetchRequest *request = [[NSFetchRequest alloc] init];    // 設定要查詢的實體    request.entity = [NSEntityDescription entityForName:@"Family" inManagedObjectContext:context];    // 設定排序(按照age降序)    //    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:NO];    //    request.sortDescriptors = [NSArray arrayWithObject:sort];    // 設定條件過濾(搜尋name中包含字串"M"的記錄,注意:設定條件過濾時,資料庫SQL語句中的%要用*來代替,所以%M%應該寫成*M*,更多過濾方法,可以看下一篇轉載文章)    //    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@", @"*M*"];    //    request.predicate = predicate;    // 執行請求    NSError *error = nil;    NSArray *objs = [context executeFetchRequest:request error:&error];    if (error) {        [NSException raise:@"查詢錯誤" format:@"%@", [error localizedDescription]];    }    // 遍曆資料    for (NSManagedObject *obj in objs) {        NSLog(@"name=%@", [obj valueForKey:@"name"]);    }    return objs;}


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.