Objective-C:iOS 10以前的Core Data

最近在把之前用Obj-C寫的作品加入一些會用到Core Data的功能,不過在最新版Xcode建立一個包含Core Data的專案都會是iOS 10的寫法,若是較舊版本的專案一樣需要用舊版的Core Data。

在網路上爬一段時間終於大概了解之前Obj-C Core Data的寫法,順便備份一下:CoreData_ObjC

首先在AppDelegate.hAppDelegate.m建立好Core Data Stack的部分,接著就能進行對Manage Object進行操作啦。

儲存:

//取用 Managed Object Context 
AppDelegate *appDelegate=(AppDelegate *)[[UIApplication sharedApplication] delegate]; NSManagedObjectContext *managedObjectContext=[appDelegate managedObjectContext];
//新增 Managed Object ,這邊Entity名稱就叫Entity
NSManagedObject *Addnumber = [NSEntityDescription insertNewObjectForEntityForName:@”Entity” inManagedObjectContext:managedObjectContext];
[Addnumber setValue:NumDisplay.text forKey:@”number”];
// 設定屬性 
NSError *error = nil; if(![managedObjectContext save:&error])
{
NSLog(@”Can’t save! %@ %@”, error, [error localizedDescription]);
// 要呼叫 save 才會儲存
}

取用:

//取用  Managed Object Context    
AppDelegate *appDelegate=(AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *managedObjectContext=[appDelegate managedObjectContext];

//取用 Entity Description
//建立一個fetch request,指定提取的entity

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entity" inManagedObjectContext: managedObjectContext];
[fetchRequest setEntity:entity];
NSError *error = nil;
//這裡用mutableArray,所以有稍微改寫,原本是NSArray    
NSMutableArray *fetchedObjects = [[ managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy];
if (fetchedObjects == nil)
{
NSLog(@"Fetch error, something's wrong. %@",error);
}
numMutArray = fetchedObjects;//存到我要放資料的陣列

刪除:

由於我的專案中是一次性刪除所有資料,因此這邊的寫法是全部刪掉

//取用  Managed Object Context
AppDelegate *appDelegate=(AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *managedObjectContext=[appDelegate managedObjectContext];

//取用 Entity Description
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entity" inManagedObjectContext: managedObjectContext];
[fetchRequest setEntity:entity];

NSError *error = nil;
NSMutableArray *fetchedObjects = [[ managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy];

if(fetchedObjects == nil)
{
NSLog(@"Delete error, something's wrong. %@",error);
}
//刪除Core data全部資料    
for(NSManagedObject *num in fetchedObjects){ [managedObjectContext deleteObject:num];
}

[numMutArray removeAllObjects]

專案參考:iOS_RandNumberCreator