No visible #interface for 'NSManagedObjectContext' declares - ios

[self.managedObjectContext deletedObjects:lastPoint];
This line shows me an error
No visible #interface for 'NSManagedObjectContext' declares the selector 'deletedObjects'.
Here is my code
can any one solve this?
Appdelegate.h
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) UIWindow *window;
#property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
#property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
#end
Appdelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
/* crete the fetch request first*/
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]initWithEntityName:#"Rectangle"];
NSError *requestError = nil;
/*And execute the fetch request on the context*/
NSArray *rectangle = [self.managedObjectContext executeFetchRequest:fetchRequest error:&requestError];
/*make sure we get the array*/
if ([rectangle count] > 0) {
/*delete the last person in the array*/
Rectangle *lastPoint = [rectangle lastObject];
[self.managedObjectContext deletedObjects:lastPoint];
if ([lastPoint isDeleted]) {
NSLog(#"Successfully deleted the last point...");
NSError *savingError = nil;
if ([self.managedObjectContext save:&savingError]) {
NSLog(#"successfully saved the context");
} else {
NSLog(#"Failed to save the context");
}
} else {
NSLog(#"Failed to delete the last point");
}
} else {
NSLog(#"Could not find any rectangle entities in the context.");
}
return YES;
}

The error message
No visible #interface for 'NSManagedObjectContext' declares the
selector 'deletedObjects'.
tells you that the class NSManagedObjectContext doesn't implement the method deletedObjects. You can check this in the API documentation.
You can use deleteObject: to delete single objects. So change your code to:
[self.managedObjectContext deleteObject:lastPoint];

As the documentation says deletedObjects is the read only property, so it has only getter method without any parameters
So you should access it just by using next
self.managedObjectContext.deletedObjects

Related

entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'Concepto'

This is the error that sends me
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'Concepto''
These are my codes CoreDataStack.h
#import "NewsManager.h"
#import "CoreData/CoreData.h"
#import <sqlite3.h>
#import Foundation;
#import CoreData;
#interface CoreDataStack : NSObject
//propiedades
#property(strong, nonatomic)NSManagedObjectContext *managedObjectContext;
#property(strong, nonatomic)NSManagedObjectModel *managedObjectModel;
#property(strong, nonatomic)NSPersistentStoreCoordinator *persistentStoreCoordinator;
#property (strong, nonatomic) UIWindow *window;
//Metodos
-(void)saveContext;
-(NSURL *)applicationDocumentsDirectory;
#end
These are my codes CoreDataStack.m
#import "CoreDataStack.h"
#implementation CoreDataStack
#synthesize window = _window;
#synthesize managedObjectContext = _managedObjectContext;
#synthesize managedObjectModel = _managedObjectModel;
#synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
#define MODEL_NAME #"Model"
#pragma mark - Core Data stack
-(NSManagedObjectContext *)ManagedObjectContext
{
if (_managedObjectContext != nil)
{
return _managedObjectContext;
}
//Pedir una NSPersistentStoreCoordinator()
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil)
{
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return _managedObjectContext;
}
//Devuelve el coordinador de almacenamiento persistente para la aplicación.
//Si el coordinador no existe, se crea y la tienda de la aplicación añade a la misma.
-(NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil)
{
return _persistentStoreCoordinator;
}
//NSString *pathString = [NSString stringWithFormat:#"%#Model.sqlite", MODEL_NAME];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"Model.splite"];
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
//NSDictionary *options = #{NSMigratePersistentStoresAutomaticallyOption:#YES, NSInferMappingModelAutomaticallyOption:#YES};
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:nil])
{
NSLog(#"error sin resolver %#, %#", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
-(NSManagedObjectModel *)managedObjectModel
{
if (_managedObjectModel != nil)
{
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"Model" withExtension:#"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}
- (void)saveContext
{
NSError *error = nil;
NSManagedObjectContext *manegedObjectContext = self.managedObjectContext;
if (manegedObjectContext != nil)
{
if ([manegedObjectContext hasChanges] && ![manegedObjectContext save:&error])
{
NSLog(#"Unresolved error %#, %#",error,[error userInfo]);
abort();
}
}
}
These are my codes ModelUtil.h
#import <UIKit/UIKit.h>
#import "IPhoneSigninViewController.h"
#import "BaseSigninViewController.h"
#import "Concepto.h"
#interface ModelUtil : BaseSigninViewController <ADDConceptos>
#property (strong, nonatomic) NSFetchedResultsController *fetchedResultsController;
#property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#end
These are my codes ModelUtil.m
#import "Concepto.h"
#import "ModelUtil.h"
#implementation ModelUtil
#synthesize fetchedResultsController = __fetchedResultsController;
#synthesize managedObjectContext = __managedObjectContext;
-(void)setupFetchedResultsController
{
// 1 - Decida lo que quiere la Entidad
NSString *entityName = #"Concepto";
// Ponga su nombre de la entidad aquí
NSLog(#"Configuración de un Controlador de resultados recuperados de la Entidad con nombre%#", entityName);
// 2 - Solicitar que la Entidad
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entityName];
// 4 - ordena los datos que se recupera
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"dato1, dato2"
ascending:YES
selector:#selector(localizedCaseInsensitiveCompare:)]];
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
}
-(void)prepareForSegue:(UIStoryboardPopoverSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"Add Concepto Segue"]) {
NSLog(#"ddddddd");
IPhoneSigninViewController *addIPhoneSigninViewController = segue.destinationViewController;
addIPhoneSigninViewController.delegate = self;
addIPhoneSigninViewController.managedObjectContext = self.managedObjectContext;
}
}
-(void)theSaveButtonOnTheAddRoleTVCWasTapped:(IPhoneSigninViewController *)controller
{
[controller.navigationController popToRootViewControllerAnimated:YES];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self setupFetchedResultsController];
}
#end
These are my codes IPhoneSigninViewController.h
//
#import "BaseSigninViewController.h"
#import <UIKit/UIKit.h>
#import "Concepto.h"
#class IPhoneSigninViewController;
#protocol ADDConceptos <NSObject>
- (void)theSaveButtonOnTheAddRoleTVCWasTapped:(IPhoneSigninViewController *)controller;
#end
#interface IPhoneSigninViewController : BaseSigninViewController <UITextFieldDelegate, UIAlertViewDelegate>
#property (nonatomic, weak)id <ADDConceptos> delegate;
- (IBAction)signinButton:(id)sender;
- (IBAction)signinCancel:(id)sender;
#property (weak, nonatomic) IBOutlet UITextField *password;
#property (weak, nonatomic) IBOutlet UITextField *email;
#property (weak, nonatomic) IBOutlet UINavigationBar *navigationBar;
#property (weak, nonatomic) IBOutlet UINavigationItem *NavigationItem;
#property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
#property (weak, nonatomic) IBOutlet UIView *formView;
#property (weak, nonatomic) IBOutlet UIButton *signupButton;
#property (weak, nonatomic) IBOutlet UIButton *remindButton;
- (void)resignOnTap:(id)iSender;
#property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#end
These are my codes IPhoneSigninViewController.m
//Guardar el email en el coredata
#pragma mark Guardar El usuario en el core data
-(void)SaveUsername
{
Concepto *cont = [NSEntityDescription insertNewObjectForEntityForName:#"Concepto" inManagedObjectContext:self.managedObjectContext];
cont.dato1 = email.text;
cont.dato2 = password.text;
[self.managedObjectContext save:nil];
[self.delegate theSaveButtonOnTheAddRoleTVCWasTapped:self];
[self SaveUsername];
}
#pragma mark Boton de inicio de secion
-(void)signinButton:(id)sender
{
NSLog(#"guardar datotes");
[self SaveUsername];
[self signInProcess];
}
one of those who already have more experience in ios I can explain how to fix the error ....
I am not sure what you are trying to achieve with these two lines -
self.managedObjectContext = [[[segue destinationViewController]viewControllers] objectAtIndex:0];
[[segue destinationViewController]setManagedObjectContext:self.managedObjectContext];
but I am fairly certain they will have the effect of setting both the current view controller and the destination view controller's managedObjectContext properties to nil or possibly to an instance of a UIViewController which is not right either. Delete these lines.
Also, by convention, variables start with a lower-case letter, so you should have -
IPhoneSigninViewController *addIPhoneSigninViewController = segue.destinationViewController;
addIPhoneSigninViewController.delegate = self;
addIPhoneSigninViewController.managedObjectContext = self.managedObjectContext;

How to pass database from AppDelegate to ViewController

I don't know why this code error.
Please help.
I read some articles and I think the problem is about context.
What Should I do?
This program is about shows data in coredata to label in viewcontroller.
AppDelegate.h
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) UIWindow *window;
#property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
#property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
#end
AppDelegate.m
#import "AppDelegate.h"
#import "Test.h"
#import "ViewController.h"
#interface AppDelegate ()
#end
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
NSManagedObjectContext *context = [self managedObjectContext];
Test *t = [NSEntityDescription insertNewObjectForEntityForName:#"Test"
inManagedObjectContext:context];
t.name = #"please";
return YES;}
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#property (weak, nonatomic) IBOutlet UILabel *label;
#property (nonatomic,strong) NSArray *temp;
#property (nonatomic,strong) NSManagedObjectContext* managedObjectContext;
#end
ViewController.m
#import "ViewController.h"
#import "Test.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize managedObjectContext;
#synthesize temp;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"Test"
inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSError *error;
self.temp = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
for(Test *info in temp){
_label.text = info.name;
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Test.h
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#interface Test : NSManagedObject
#property (nonatomic, retain) NSString * name;
#end
Test.m
#import "Test.h"
#implementation Test
#dynamic name;
#end
I don't know why this code error.
Please help.
I read some articles and I think the problem is about context.
What Should I do?
In your view controller, replace the line:
#synthesize managedObjectContext;
With this:
- (NSManagedObjectContext *) managedObjectContext {
return ((AppDelegate *)[[UIApplication sharedApplication] delegate]).managedObjectContext;
}
Instead of storing another, different object context in your view controller, this property will return the object context that you set up in the app delegate.
There are other ways to do this, such as creating a Core Data helper class following the Singleton pattern (as #NewYork167 suggests), but this should at least solve your current problem.
For any future reference, you can also try subclassing the NSManagedObjectContext like this:
#interface MyManagedObjectContext : NSManagedObjectContext
+ (MyManagedObjectContext *)mainThreadContext;
#end
#implementation MyManagedObjectContext
+ (MyManagedObjectContext *)mainThreadContext;
{
static MyManagedObjectContext *moc;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
moc = [[self alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
// Setup persistent store coordinator here
});
return moc;
}
#end
Reference: Best practices for passing NSManagedObjectContext around to UITabBarController child view controllers?

Not able to display results in the console

I made an application for storing data in CD. I want to just simply write the things into the console but I can't get printed on the console. Am I doing something wrong?
Here is my code whole demo application.
Here is my screen shot of Core_Data_Demo_xcdatamodeld
// AppDelegate.h
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) UIWindow *window;
#property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
#property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
#end
// AppDelegate.h
-(BOOL)createNewRectangleWithHeight:(NSInteger)heightParam width:(NSInteger)widthParam{
if (heightParam ==0 || widthParam ==0) {
NSLog(#"The height and width must no be 0");
return NO;
}
Rectangle *rect = [NSEntityDescription insertNewObjectForEntityForName:#"Rectangle" inManagedObjectContext:self.managedObjectContext];
if (rect == nil) {
NSLog(#"Failed to create new Rectangle");
return NO;
}
rect.height = [NSNumber numberWithInt:heightParam];
rect.width = [NSNumber numberWithInt:widthParam];
NSError *savingError = nil;
if ([self.managedObjectContext save:&savingError]) {
return YES;
} else {
NSLog(#"Failed to save new person. Error = %# ",savingError);
}
return YES;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self createNewRectangleWithHeight:2 width:2];
return YES;
}
You are not able to see any statements because (I suppose) things run correctly.
If you want to retrieve data and print in the console you need to run a different method like printData or whatever you want. This method should set up a NSFetchRequest and execute it against your entity Rectangle.
- (void)printData {
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"Rectangle"];
NSError *error = nil;
NSArray *results = [self.managedObjectContext executeFetchRequest:request error:&error];
if(error) {
// An error occurred
} else {
// See the results
}
}
Usage
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// [self createNewRectangleWithHeight:2 width:2];
[self printData];
return YES;
}
You should comment the createNew... method otherwise you will see multiple entries (equal to the number of times you've run the application) of Rectangle objects with the same width and height.
The code which you have shown is for adding values using core data, If you do not get any error in the NSError object while you are adding the values then data is successfully added inside the sqlite file.
To check the added values what you can do is use the SqliteManager addon from firefox and open the sqlite file (You can get the sqlite file location using NSHomeDirectory() method for it and then jump to the documents folder).
If you don't want the addon way you can always use NSFetchRequest to pull your data given below is the code for the same
- (NSManagedObjectContext*)getManagedObjectContext{
AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
return appDelegate.managedObjectContext;
}
- (void)fetchdataFromDatabase{
NSManagedObjectContext *appContext = [self getManagedObjectContext];
if(appContext!=nil){
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"YOUR_ENTITY_NAME" inManagedObjectContext:appContext];
[fetchRequest setEntity:entity];
NSError *error = nil;
NSArray *fetchedObjects = [appContext executeFetchRequest:fetchRequest
error:&error];
if(error!=nil && fetchedObjects.count!=0){
// print your data here
}else{
//Print the error here
}
}
}

Core Data - failing to load data, entity not found

I have created a simple 1 entity data model through Core Data. I add an entity in "didFinishLaunchingWithOptions" of "AppDelegate". Then, I am trying to load the data of the model to an array and then a table view.
I am aware that there are similar post, but I still can't find out whats wrong with my code.
List of things I have tried and checked:
The entity is added properly into the model
I have already checked the entity names and they are correct.
I have tried deleting the app and clean rebuilding it but still nothing.
So there must be a more major issue with my code. Any help is appreciated.
Here is my error:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '+entityForName: could not locate an NSManagedObjectModel for entity name 'FavoritesInfo'
AppDelegate.h
#import <UIKit/UIKit.h>
#import "favTable.h"
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (strong, nonatomic) UIWindow *window;
#property (strong, nonatomic) favTable *viewController;
#property (strong, nonatomic) UINavigationController *navController;
#property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
#property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
#property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (NSURL *)applicationDocumentsDirectory; // reference files for core data
#end
AppDelegate.m
#import "AppDelegate.h"
#implementation AppDelegate
#synthesize window = _window;
#synthesize viewController = _viewController;
#synthesize navController = _navController;
#synthesize managedObjectContext = _managedObjectContext;
#synthesize managedObjectModel = _managedObjectModel;
#synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *favoritesInfo = [NSEntityDescription
insertNewObjectForEntityForName:#"FavoritesInfo"
inManagedObjectContext:context];
[favoritesInfo setValue:#"Product 1" forKey:#"name"];
[favoritesInfo setValue:[NSNumber numberWithInt:15] forKey:#"score"];
NSError *error;
if (![context save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
return YES;
}
Then in the class of the table viewcontroller favtable.h
#import <UIKit/UIKit.h>
#interface favTable : UITableViewController <NSFetchedResultsControllerDelegate>
{
NSFetchedResultsController *fetchedResultsController;
NSManagedObjectContext *managedObjectContext;
NSArray *favArr;
int num;
}
#property (nonatomic, strong) NSArray *favArr;
#property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
#property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController;
#end
favtable.m viewdidload
#import "favTable.h"
#import "AppDelegate.h"
#interface favTable ()
#end
#implementation favTable
#synthesize favArr;
#synthesize spVC;
#synthesize managedObjectContext = _managedObjectContext;
#synthesize fetchedResultsController;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Favorites";
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"FavoritesInfo" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSError *error=nil;
self.favArr=[managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (error!=nil) {
NSLog(#" fetchError=%#,details=%#",error,error.userInfo);
}
}
Your managedObjectContext is not set in your ViewController.
Set it in your AppDelegate didFinishLaunchingWithOptions, usually looks like:
ViewControllerClass *controller = (ViewControllerClass*)self.window.rootViewController;
or with a navigation controller:
UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;
ViewControllerClass *controller = (ViewControllerClass *)navigationController.topViewController;
And then:
controller.managedObjectContext = self.managedObjectContext;
In my favtable.m class I added this to set the managedObjectContext and it works properly.
self.managedObjectContext = ((AppDelegate *) [UIApplication sharedApplication].delegate).managedObjectContext;

Multiple xcdatamodel files in Xcode

My project(for managing students' attendance in various classes) contains 2 xkcddatamodel files, one for the semester start/end dates and the other for the course data. If you look at AppDelegate.m, I've set the modelURL to the second model. How am I supposed to create a second context for the first xkcddatamodel? I've tried the solution given here. But no dice. Xcode isn't even recognising it and is asking me to replace managedObjectContext2 with managedObjectContext. How do I fix this?
Dropbox link to the project: https://www.dropbox.com/sh/ivl6nw6nw8p9j1y/MDwYDaHVH_
Here's the AppDelegate.m
//
// AppDelegate.m
// timetable app
//
// Created by Robin Malhotra on 22/12/13.
// Copyright (c) 2013 Robin's code kitchen. All rights reserved.
//
#import "AppDelegate.h"
#import <CoreData/CoreData.h>
#implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
return YES;
}
// Explicitly write Core Data accessors
- (NSManagedObjectContext *) managedObjectContext {
if (managedObjectContext != nil) {
return managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator: coordinator];
}
return managedObjectContext;
}
- (NSManagedObjectModel *)managedObjectModel {
if (managedObjectModel != nil) {
return managedObjectModel;
}
// removed some code about retain here as ARC hates that
return managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator != nil) {
return persistentStoreCoordinator;
}
NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory]
stringByAppendingPathComponent: #"Courses.sqlite"]];
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"ClassesAttended" withExtension:#"momd"];
managedObjectModel=[[NSManagedObjectModel alloc]initWithContentsOfURL:modelURL];
NSError *error = nil;
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]
initWithManagedObjectModel:[self managedObjectModel]];
if(![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil URL:storeUrl options:nil error:&error]) {
/*Error for store creation should be handled in here*/
}
return persistentStoreCoordinator;
}
- (NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
/* (...Existing Application Code...) */
-(NSArray *)getAllCourses
{
NSFetchRequest *request=[[NSFetchRequest alloc]init];
NSEntityDescription *entitydesc=[NSEntityDescription entityForName:#"Course" inManagedObjectContext:managedObjectContext];
[request setEntity:entitydesc];
NSError *error;
NSArray *fetchedCourses=[self.managedObjectContext executeFetchRequest:request error:&error];
return fetchedCourses;
}
#end
and here's the AppDelegate.h
#import <UIKit/UIKit.h>
#interface AppDelegate : UIResponder <UIApplicationDelegate>
{
NSManagedObjectModel *managedObjectModel;
NSManagedObjectContext *managedObjectContext;
NSPersistentStoreCoordinator *persistentStoreCoordinator;
}
#property (strong, nonatomic) UIWindow *window;
#property (nonatomic, readonly) NSManagedObjectModel *managedObjectModel;
#property (nonatomic, readonly) NSManagedObjectContext *managedObjectContext;
#property (nonatomic, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
#property (nonatomic, readonly) NSManagedObjectModel *managedObjectModel2;
#property (nonatomic, readonly) NSManagedObjectContext *managedObjectContext2;
#property (nonatomic, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator2;
- (NSString *)applicationDocumentsDirectory;
- (NSArray *)getAllCourses;
#end

Resources