CoreData入門

CoreData入門

CoreData是蘋果提供的實現(xiàn)SQLite關(guān)系型數(shù)據(jù)庫的持久化的框架,具有面向?qū)ο罄砟詈蛯ο?關(guān)系映射功能,不用使用SQL語句,但是我對于它想說臟話。如果真的需要使用建議使用第三方庫:MagicalRecord.

使用入門

  • 新建項目的時候要勾選上Use Core Data。
  • 會在項目生成.xcdatamodeld后綴的灰色文件,并且在AppDelegate生成模型。
屏幕快照 2016-01-29 上午9.48.51.png
  • 查看.xcdatamodeld后綴的灰色文件并且可以在里面編寫數(shù)據(jù)庫屬性查看編寫后的格式。
屏幕快照 2016-01-29 上午9.51.50.png
  • 添加數(shù)據(jù)示例
#import "ViewController.h"
#import "LXKStudent.h"
#import "AppDelegate.h"

@interface ViewController () {
    NSManagedObjectContext *_ctx;
}

@property (weak, nonatomic) IBOutlet UILabel *namaLabel;
@property (weak, nonatomic) IBOutlet UILabel *ageLabel;
@property (weak, nonatomic) IBOutlet UILabel *stuidLabel;
@property (weak, nonatomic) IBOutlet UIImageView *photoImageView;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    AppDelegate *appDel = (id)[UIApplication sharedApplication].delegate;
    _ctx = appDel.managedObjectContext;
    
#if 0
    // 居然可以重復(fù)寫入一樣的
    LXKStudent *stu = [NSEntityDescription insertNewObjectForEntityForName:@"LXKStudent" inManagedObjectContext:_ctx];
    
    stu.stuid = @(1234);
    stu.name = @"牧月";
    stu.age = @(18);
    stu.photo = UIImagePNGRepresentation([UIImage imageNamed:@"5.jpg"]);

    NSError *err = nil;
    [_ctx save:nil];
    
    NSLog(@"%@",err? @"失敗": @"成功");
#endif
    
    //直接使用fetch就出來了
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"LXKStudent" inManagedObjectContext:_ctx];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"stuid=%@", @(1234)];
    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    
//    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"<#key#>"
//                                                                   ascending:YES];
//    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [_ctx executeFetchRequest:fetchRequest error:&error];
    LXKStudent *stu = fetchedObjects[2];
    _stuidLabel.text = [stu.stuid stringValue];
    _namaLabel.text = stu.name;
    _ageLabel.text = [stu.age stringValue];
    _photoImageView.image = [UIImage imageWithData:stu.photo];
    
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容