sco*_*pio 5 core-data objective-c nsmanagedobjectcontext swift xcode8
我正在尝试使用CoreData,但是当我将它添加到我的项目中时,我只获得了两个新方法:
- (NSPersistentContainer *)persistentContainer
Run Code Online (Sandbox Code Playgroud)
和
- (void)saveContext
Run Code Online (Sandbox Code Playgroud)
现在我无法使用旧的方法CoreData,我找不到任何有这些新方法和Objective-C的教程.如何CoreData使用persistentContainerObjective-c在Xcode 8中保存和获取数据?
Nik*_*ure 16
您可以获取上下文 -
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
Run Code Online (Sandbox Code Playgroud)
或者如在Objective-C中那样
NSManagedObjectContext *context = ((AppDelegate*)[[UIApplication sharedApplication] delegate]).persistentContainer.viewContext;
Run Code Online (Sandbox Code Playgroud)
并获取数据 - 如
var resultArray = try self.context.fetch(EntityName.fetchRequest())
Run Code Online (Sandbox Code Playgroud)
或者如在Objective-C中那样
NSFetchRequest<EntityName *> *fetchRequest = [EntityName fetchRequest];
NSError *error ;
NSArray *resultArray= [context executeFetchRequest:fetchRequest error:&error];
Run Code Online (Sandbox Code Playgroud)
并通过排序获取数据 -
var resultArray = [EntityName]()
do {
let request : NSFetchRequest<EntityName> = EntityName.fetchRequest()
let sortDescriptor = NSSortDescriptor(key: "somekey", ascending: true)
let sortDescriptors = [sortDescriptor]
request.sortDescriptors = sortDescriptors
resultArray = try self.context.fetch(request)
} catch {
print("Error")
}
Run Code Online (Sandbox Code Playgroud)
或者如在Objective-C中那样
NSFetchRequest<EntityName *> *fetchRequest = [EntityName fetchRequest];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"someKey" ascending:YES];
fetchRequest.sortDescriptors = @[sortDescriptor];
NSError *error ;
NSArray *resultArray= [context executeFetchRequest:fetchRequest error:&error];
Run Code Online (Sandbox Code Playgroud)
并添加像 -
let entityNameObj = EntityName(context: context)
entityNameObj.title = "title"
Run Code Online (Sandbox Code Playgroud)
或者如在Objective-C中那样
NSManagedObject *entityNameObj = [NSEntityDescription insertNewObjectForEntityForName:@"EntityName" inManagedObjectContext:context];
[entityNameObj setValue:@"someValue" forKey:@"someKey"];
Run Code Online (Sandbox Code Playgroud)
并保存上下文,如 -
do {
try self.context.save()
} catch _ as NSError {
print("Error")
}
Run Code Online (Sandbox Code Playgroud)
或者如在Objective-C中那样
[((AppDelegate*)[[UIApplication sharedApplication] delegate]) saveContext];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7292 次 |
| 最近记录: |