CoreData入门

CoreData入门

CoreData是苹果提供的实现SQLite关系型数据库的持久化的框架,具有面向对象理念和对象-关系映射功能,不用使用SQL语句,但是我对于它想说脏话。如果真的需要使用建议使用第三方库:MagicalRecord.

使用入门

  • 新建项目的时候要勾选上Use Core Data。
  • 会在项目生成.xcdatamodeld后缀的灰色文件,并且在AppDelegate生成模型。
CoreData入门_第1张图片
屏幕快照 2016-01-29 上午9.48.51.png
  • 查看.xcdatamodeld后缀的灰色文件并且可以在里面编写数据库属性查看编写后的格式。
CoreData入门_第2张图片
屏幕快照 2016-01-29 上午9.51.50.png
  • 添加数据示例
#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
    // 居然可以重复写入一样的
    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];
    
}

你可能感兴趣的:(CoreData入门)