CoreData入门

2016-01-29  本文已影响153人  LennonLin

CoreData入门

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

使用入门

屏幕快照 2016-01-29 上午9.48.51.png 屏幕快照 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];
    
}
上一篇下一篇

猜你喜欢

热点阅读