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];
}