iOS开发新手。我正在尝试在示例应用程序中使用核心数据堆栈,该应用程序通过网络获取数据并简单地更新UI。在创建项目时,勾选了“使用核心数据”复选框,该复选框会生成许多样板代码。但是,在XCode 8.2.1
上,我只看到NSPersistentContainer
文件中的AppDelegate.m
实现。
- (NSPersistentContainer *)persistentContainer {
// The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
@synchronized (self) {
if (_persistentContainer == nil) {
_persistentContainer = [[NSPersistentContainer alloc] initWithName:@"ergast_coredata_objc"];
[_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
if (error != nil) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
NSLog(@"Unresolved error %@, %@", error, error.userInfo);
abort();
}
}];
}
}
return _persistentContainer;
}
NSManagedObjectContext
没有样板代码,因为大多数教程都会让您相信。
因此,ViewController.m
类中的以下块因
-(NSArray *)getSeasonsList{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"SeasonData"];
NSError *error = nil;
NSArray *results = [[self getManagedObjectContext] executeFetchRequest:request error:&error];
if (!results) {
NSLog(@"Error fetching objects: %@\n%@", [error localizedDescription], [error userInfo]);
abort();
}
return results;
}
- (NSManagedObjectContext *)getManagedObjectContext {
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
context = [delegate managedObjectContext];
return context;
}
尝试在线查看,但大多数教程都是以Swift为基础的。我在这里失踪了什么?开发人员是否应该为NSManagedObjectContext
提供实施?如果有人可以提供基于Objective-c的示例代码,将非常感激。
谢谢!
答案 0 :(得分:1)
- (void)saveContext {
// OBSERVE HERE
NSManagedObjectContext *context = self.persistentContainer.viewContext;
NSError *error = nil;
if ([context hasChanges] && ![context save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, error.userInfo);
abort();
}
}
方法NSManagedObjectContext *context = self.persistentContainer.viewContext;
self.persistentContainer
classObject.persistentContainer
或 public class UserEntity
{
[PrimaryKey, AutoIncrement]
public int id { get; set; }
public int employee_id { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string email { get; set; }
public string login_id { get; set; }
public string login_password { get; set; }
public int role { get; set; }
public bool is_delete { get; set; }
public UserEntity()
{
}
public UserEntity(UserEntity userEntity)
{
this.id = userEntity.id;
this.employee_id = userEntity.employee_id;
this.first_name = userEntity.first_name;
this.email = userEntity.email;
this.login_id = userEntity.login_id;
this.login_password = userEntity.login_password;
this.role = userEntity.role;
this.is_delete = false;
}
}
public class UserModel : UserEntity
{
public UserModel(UserEntity userEntity) : base(userEntity)
{
}
}
答案 1 :(得分:0)
修改“getManagedObjectContext”方法,如下所示
- (NSManagedObjectContext *)getManagedObjectContext {
AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [[delegate persistentContainer] viewContext];
return context;
}
我没有测试过这个,但希望这会有效
答案 2 :(得分:0)
我有一个appdelegate的类别,它包含在一个使用objective-c的旧斯坦福CS193P中。但有些可能会被弃用。另请查看https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/InitializingtheCoreDataStack.html#//apple_ref/doc/uid/TP40001075-CH4-SW1有objective-c示例。回帖如果有帮助的话。
//
// PhotomaniaAppDelegate+MOC.m
// Photomania
//
// This code comes from the Xcode template for Master-Detail application.
#import "PhotomaniaAppDelegate+MOC.h"
#import <CoreData/CoreData.h>
@implementation PhotomaniaAppDelegate (MOC)
#pragma mark - Core Data
- (void)saveContext:(NSManagedObjectContext *)managedObjectContext
{
NSError *error = nil;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}
// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)createMainQueueManagedObjectContext
{
NSManagedObjectContext *managedObjectContext = nil;
NSPersistentStoreCoordinator *coordinator = [self createPersistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return managedObjectContext;
}
// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)createManagedObjectModel
{
NSManagedObjectModel *managedObjectModel = nil;
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Photomania" withExtension:@"momd"];
managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return managedObjectModel;
}
// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)createPersistentStoreCoordinator
{
NSPersistentStoreCoordinator *persistentStoreCoordinator = nil;
NSManagedObjectModel *managedObjectModel = [self createManagedObjectModel];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"MOC.sqlite"];
NSError *error = nil;
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
Typical reasons for an error here include:
* The persistent store is not accessible;
* The schema for the persistent store is incompatible with current managed object model.
Check the error message to determine what the actual problem was.
If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
@{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}
Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
*/
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return persistentStoreCoordinator;
}
// Returns the URL to the application's Documents directory
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
@end
另外,请查看此项目https://github.com/m2mtech/photomania-2013-14/tree/master/Photomania/CoreDataTableViewController/MOC了解更多信息Core Data如何与此实施一起使用。