我是CoreData的新手。我正在使用精灵套件来创建游戏。我在appdelegate.h和appdelegate.m中将核心数据设置到我的项目中。我可以使用以下代码
在appdelegate中获取数据NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Current" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSError *error;
NSLog(@"%@",[self.managedObjectContext executeFetchRequest:fetchRequest error:&error]);
我想在另一个类(视图)中获取数据。我无法获取managedObjectContext对象,因为我无法调用self.managedObjectContext。 我应该怎么做才能从另一个类中获取coredata?
答案 0 :(得分:1)
你必须拥有一些带有NSManagedObjectContext的类,例如'DBManger'
@interface DBManager : NSObject
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
@end
在ViewController中使用:
DBManager *dbManager = [[DBManager alloc] init];
NSManagedObjectContext *context = dbManager.managedObjectContext;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Current" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSError *error;
NSLog(@"%@",[self.managedObjectContext executeFetchRequest:fetchRequest error:&error]);
如果您的ManagedContext在AppDelegate中,请获取它:
NSManagedObjectContext *context = ((AppDelegate*)[UIApplication sharedApplication].delegate).managedObjectContext;