' entityForName: nil is not a legal NSManagedObjectContext -CoreData - iphone

I am getting this error when running the app:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason:
'+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity
name 'Event''
This is my TimeTableController.h file (TimeTableController is a subclass UITableViewController and app loads this file when app stared.
TimeTableController.h:
#import "Event.h"
#interface TimeTableController : UITableViewController
{
NSManagedObjectContext *managedObjectContext;
NSMutableArray *eventArray;
}
#property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
#property (nonatomic, retain) NSMutableArray *eventArray;
- (void) fetchRecords;
- (void) addTime:(id)sender;
#end
Event.h and Event.m are my model files.
And TimeTableController.m
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Lap Times";
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(addTime:)];
self.navigationItem.rightBarButtonItem = addButton;
//[addButton release];
[self fetchRecords];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
-(void)fetchRecords {
// This line gives the error
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Event" inManagedObjectContext:managedObjectContext];
}
The line in fetchRecords method is giving the error.
And this is my AppDelegate.m file:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
TimeTableController *tableController = [[TimeTableController alloc] initWithStyle:UITableViewStylePlain];
tableController.managedObjectContext = [self managedObjectContext];
self.navigationController = [[UINavigationController alloc] initWithRootViewController:tableController];
//[tableController release];
[window addSubview: [self.navigationController view]];
[window makeKeyAndVisible];
return YES;
}
When I've created the project,Data Model file didn't exist so I've added the Data Model file (LapTimer.xcdatamodeld) to existing project.
I tried all solutions I found and I have no idea why I am getting this error now.
Note: I know there are a lot of threads that cover exactly this questions. I looked at all but none of answers didn't work for me.

I was getting the same error message and it turns out that managedObjectContext was nil.

Related

MWPhotoBrowser with button and error handeling

I'm trying to make a app that uses a photobrowser
Decided to go with the MWPhotoBrowser.
This is the code, but i cant seem to make it work:
ViewController.h
#import <UIKit/UIKit.h>
#import "MWPhotoBrowser.h"
#interface ViewController : UIViewController<MWPhotoBrowserDelegate> {
NSArray *_photos;
UISegmentedControl *_segmentedControl;
}
#property (nonatomic, retain) NSArray *photos;
- (IBAction)billede:(id)sender;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize photos = _photos;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
UIBarButtonItem *item = [[[UIBarButtonItem alloc] initWithCustomView:_segmentedControl] autorelease];
self.navigationItem.rightBarButtonItem = item;
self.navigationItem.backBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:#"Back" style:UIBarButtonItemStyleBordered target:nil action:nil] autorelease];
}
return self;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (IBAction)billede:(id)sender {
//show your photo whit url
NSMutableArray *photos = [[NSMutableArray alloc] init];
MWPhoto *photo;
{
photo = [MWPhoto photoWithFilePath:[[NSBundle mainBundle] pathForResource:#"photo2l" ofType:#"jpg"]];
photo.caption = #"The London Eye is a giant Ferris wheel situated on the banks of the River Thames, in London, England.";
[photos addObject:photo];
}
self.photos = photos;
// Create browser
MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
browser.displayActionButton = YES;
//browser.wantsFullScreenLayout = NO;
//[browser setInitialPageIndex:2];
// Show
if (_segmentedControl.selectedSegmentIndex == 0) {
// Push
[self.navigationController pushViewController:browser animated:YES];
} else {
// Modal
UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:browser];
nc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController:nc animated:YES];
[nc release];
}
}
#pragma mark - MWPhotoBrowserDelegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
return _photos.count;
}
- (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex: (NSUInteger)index {
if (index < _photos.count)
return [_photos objectAtIndex:index];
return nil;
}
#end
I've tried both with ARC and wothout ARC
Without ARC i get 3 errors:
Undefined symbols for architecture i386:
"_OBJC_CLASS_$_MWPhoto", referenced from:
objc-class-ref in ViewController.o
"_OBJC_CLASS_$_MWPhotoBrowser", referenced from:
objc-class-ref in ViewController.o
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)
With ARC i get 2 errors
Problem 1
http://i.imgur.com/pT7qW.png
Problem 2
http://i.imgur.com/E0X1m.png
I've not done it here, but i would like it alle to be wrapped in a button so i can click that and show a image inside the MWPhotoBrowser
Edit
I have upgraded my code, removed ARC from my files and i have now set the target right.
It will compile now, but everytime i triy to click the button: "billede" i get:
2012-11-26 23:32:10.955 MWPhotoBrowserTest[10405:c07] -[ViewController galleri:]: unrecognized selector sent to instance 0x947fb20
2012-11-26 23:32:10.957 MWPhotoBrowserTest[10405:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ViewController galleri:]: unrecognized selector sent to instance 0x947fb20'
*** First throw call stack:
(0x1d34012 0x14e9e7e 0x1dbf4bd 0x1d23bbc 0x1d2394e 0x14fd705 0x434920 0x4348b8 0x4f5671 0x4f5bcf 0x4f4d38 0x46433f 0x464552 0x4423aa 0x433cf8 0x1f6ddf9 0x1f6dad0 0x1ca9bf5 0x1ca9962 0x1cdabb6 0x1cd9f44 0x1cd9e1b 0x1f6c7e3 0x1f6c668 0x43165c 0x1e2d 0x1d55)
libc++abi.dylib: terminate called throwing an exception
(lldb)
Attachment 1:
You can't add objects to NSArray, use NSMutableArray instead.
Attachment 2:
UIView has no methods "reloadData", but for exmple UITableView does.
Actually resolved this.
I've struggled for 4 days and finally got it.
I read through https://github.com/mwaterfall/MWPhotoBrowser#method-1-static-library and understood it, finally but i had a problem with User header Search Path.
I finally got it, importet MWPhotoBrowser folder into my MWPhotoBrowser"project" folder and then sat User Header Search Path to ".." instead of "../" since "../" gave me "../../"
Hope this helps anyone who might stand in the same problem as me!
Btw, thanks for the help guys! :-)

Trying to make my iphone app universal. Navigation Controller keeps saying Unbalanced calls

have been trying couple of hours now to make my iphone app universal. The mission was successful but have a strange problem. The navigation controller keeps pushing things without even pushing anything. The app doesn't crash but it gives me a message in the console
nested push animation can result in corrupted navigation bar
2012-02-06 10:52:07.701 ##$%^^$[54755:207] Finishing up a navigation transition in an unexpected state. Navigation Bar subview tree might get corrupted.
2012-02-06 10:52:07.704 !##$%^$%#[54755:207] Unbalanced calls to begin/end appearance transitions for <searchEditViewController: 0xc652150>.
and here is how i've set app the whole thing :
![navigation screen shot][1]
here is my code in the AppDelegate_iphone.h
#import <UIKit/UIKit.h>
#import "iPhoneView.h"
#import "AboutUsViewController.h"
#import "FavoritesViewController.h"
#class iPhoneView;
#interface AppDelegate_iPhone : NSObject <UIApplicationDelegate> {
UITabBarController *tabBarController;
UINavigationController *homeNavigationController;
UINavigationController *favouritesNavigationController;
AboutUsViewController *aboutUsViewController;
iPhoneView * search;
FavoritesViewController *favoritesViewController;
UIWindow *window;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet iPhoneView *search;
#property (nonatomic, retain) FavoritesViewController *favoritesViewController;
#end
and here is on my AppDelegate.m file
#import "AppDelegate_iPhone.h"
#import "iPhoneView.h"
#implementation AppDelegate_iPhone
#synthesize window,search,favoritesViewController;
#pragma mark -
#pragma mark Application lifecycle
- (void)applicationDidFinishLaunching:(UIApplication *)application
{ tabBarController = [[UITabBarController alloc] init];
homeNavigationController = [[UINavigationController alloc] init];
search = [[iPhoneView alloc] init];
[homeNavigationController pushViewController:search animated:NO];
favouritesNavigationController = [[UINavigationController alloc] init];
favoritesViewController = [[FavoritesViewController alloc]init];
[favouritesNavigationController pushViewController:favoritesViewController animated:NO];
aboutUsViewController =[[AboutUsViewController alloc] init];
UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:#"επικοινωνία" image:[UIImage imageNamed:#"aboutus"] tag:0];
aboutUsViewController.tabBarItem = item;
[item release];
UITabBarItem *item2 = [[UITabBarItem alloc] initWithTitle:#"αγαπημένα" image:[UIImage imageNamed:#"favorites"] tag:0];
favouritesNavigationController.tabBarItem = item2;
[item2 release];
NSArray *tabBarControllerCollection = [NSArray arrayWithObjects:homeNavigationController,favouritesNavigationController,aboutUsViewController,nil];
[tabBarController setViewControllers:tabBarControllerCollection animated:NO];
[window addSubview:tabBarController.view];
[window makeKeyAndVisible];
}
- (void)applicationWillResignActive:(UIApplication *)application {
/*
Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
*/
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
/*
Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
*/
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
/*
Called as part of transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
*/
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
/*
Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
*/
}
- (void)applicationWillTerminate:(UIApplication *)application {
/*
Called when the application is about to terminate.
See also applicationDidEnterBackground:.
*/
}
#pragma mark -
#pragma mark Memory management
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
/*
Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
*/
}
- (void)dealloc {
[tabBarController release];
[search release];
[favoritesViewController release];
[favouritesNavigationController release];
[aboutUsViewController release];
[window release];
[super dealloc];
}
#end
OK solved had connected the button 2 times with the same action in IB. Took me 48hours to figure it out!

How to open the Edit contact window in iphone app?

I am adding contact info from my iPhone application on Addcontact click. I just want to open edit contact window on same Addcontact click so user can edit or delete the contact which just now have added. I have done smthing like below..
- (IBAction)AddContact
{
ABAddressBookRef addressBook = ABAddressBookCreate();
ABRecordRef Showroom = ABPersonCreate();
//adding contact name as showroom name
ABRecordSetValue(Showroom, kABPersonFirstNameProperty, ShowroomName.text , nil);
ABAddressBookAddRecord(addressBook, Showroom, nil);
ABAddressBookSave(addressBook, nil);
// Fetch the address book
//ABAddressBookRef addressBook = ABAddressBookCreate();
// Search for the person named "Appleseed" in the address book
//ABRecordRef Showroom = (ABRecordRef)[Showroom objectAtIndex:0];
ABPersonViewController *picker = [[[ABPersonViewController alloc] init] autorelease];
picker.personViewDelegate = self;
picker.displayedPerson = Showroom;
// Allow users to edit the person’s information
picker.allowsEditing = YES;
[self.navigationController pushViewController:picker animated:YES];
}
this is my Map application. On launching I get showroom results with there contacts. This I can add in to the iPHone contact with edit contact window opening. But when I open other controller to pass user selected string address in to Map controller to search showroom location. The same above code is not working. I mean it only add the contacts but I didnt get the edit contact window.
Edit:
May be this problem is regarding navigation controller bar so check the below code also
- (void)viewWillAppear:(BOOL)animated
{
[self.navigationController setNavigationBarHidden:YES animated:animated];
}
- (void)viewDidLoad {
[self.navigationController setNavigationBarHidden:NO ];
self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:25.0/255.0f green:25.0/255.0f blue:25.0/255.0f alpha:1.0f];
}
- (void)viewWillDisappear:(BOOL)animated
{
[self.navigationController setNavigationBarHidden:NO animated:animated];
}
I hope this code is works for you i implements that code and in my application works fine thank you
contecviewcontroller.h
#interface DetailsViewController : UIViewController
DocumentNavController *coffeeObj;
editViewController *evController;
int currentindex;
}
#property (nonatomic, retain) DocumentNavController *coffeeObj;
#property (readwrite, assign) int currentindex;
#end
contecviewcontroller.m
- (void)viewDidLoad {
[super viewDidLoad];
//self.navigationController.toolbar.tintColor = [UIColor darkGrayColor];
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemEdit
target:self action:#selector(goToEdit)]autorelease];
}
-(void)goToEdit{
if(evController == nil)
evController = [[editViewController alloc]initWithNibName:#"editViewController" bundle:nil];
evernoteAppDelegate *appdelegete = (evernoteAppDelegate *)[[UIApplication sharedApplication]delegate];
coffeeObj = [appdelegete.noteArray objectAtIndex:currentindex];
evController.Editcurrentindex = currentindex;
evController.docedObj = coffeeObj;
[self.navigationController pushViewController:evController animated:YES];
}

releasing objects?

I'm really new to iPhone programming.
This app is a simple quiz. FirstAppDelegate.m creates an instance of QuizViewController and adds its view to the window.
#import "FirstAppDelegate.h"
#import "ResultViewController.h"
#import "QuizViewController.h"
#implementation FirstAppDelegate
#synthesize window;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions (NSDictionary *)launchOptions {
UIViewController *vc = [[QuizViewController alloc] init];
[window addSubview:[vc view]];
[window makeKeyAndVisible];
[vc release];
return YES;
}
- (void)dealloc {
[window release];
[super dealloc];
}
#end
I thought I could release vc like I do hear since window will retain it (?) but it generated an error :
2011-06-28 23:06:34.190 First[14289:207] -[__NSCFType foo:]: unrecognized selector sent to instance 0x4e1fc90
2011-06-28 23:06:34.193 First[14289:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFType foo:]: unrecognized selector sent to instance 0x4e1fc90'
...so I commented it and now it works fine. But where should I release vc? Here's QuizViewController.h:
#import <UIKit/UIKit.h>
#interface QuizViewController : UIViewController {
IBOutlet UILabel *questionLabel;
IBOutlet UIButton *button1;
IBOutlet UIButton *button2;
IBOutlet UIButton *button3;
int currentQuestionIndex;
int corrects;
NSMutableArray *questions;
NSMutableArray *answers;
NSMutableArray *correctAnswers;
}
- (IBAction)foo:(id)sender;
#end
...and QuizViewController.m:
#import "QuizViewController.h"
#implementation QuizViewController
- (id)init {
NSLog(#"QuizViewController init");
[super initWithNibName:#"QuizViewController" bundle:nil];
questions = [[NSMutableArray alloc] init];
answers = [[NSMutableArray alloc] init];
correctAnswers = [[NSMutableArray alloc] init];
[questions addObject:#"Vad betyder det engelska ordet \"though\"?"];
[answers addObject:#"Tuff"];
[answers addObject:#"Dock"];
[answers addObject:#"Tanke"];
[correctAnswers addObject:#"Dock"];
[questions addObject:#"Vad hette frontpersonen i Popbandet Queen?"];
[answers addObject:#"Pierre Bouviere"];
[answers addObject:#"Freddie Mercury"];
[answers addObject:#"Stevie Wonder"];
[correctAnswers addObject:#"Freddie Mercury"];
return self;
}
- (IBAction)foo:(id)sender {
NSLog(#"foo");
}
- (void)loadView {
NSLog(#"QuizViewController loadView");
[questionLabel setText:[questions objectAtIndex:currentQuestionIndex]];
[button1 setTitle:[answers objectAtIndex:currentQuestionIndex] forState:UIControlStateNormal];
[button2 setTitle:[answers objectAtIndex:currentQuestionIndex + 1] forState:UIControlStateNormal];
[button3 setTitle:[answers objectAtIndex:currentQuestionIndex + 2] forState:UIControlStateNormal];
[super loadView];
}
- (void)viewDidLoad {
NSLog(#"QuizViewController viewDidLoad");
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
- (void)dealloc {
[super dealloc];
}
#end
You should create an instance variable to hold the VC. The reason you are losing it when you release it is that the window is only retaining the view and not the controller.
I thought I could release vc like I do hear since window will retain it...
Notice that you are adding the view associated to the view controller ([vc view]) to your UIWindow. That object will be retained, not your controller.
You can fix this by defining a variable in your FirstAppDelegate to store the controller there and release it in FirstAppDelegate dealloc.
#interface FirstAppDelegate
.....
#property (nonatomic, retain) QuizViewController* controller;
.....
#end
#implementation FirstAppDelegate
#synthesize window;
#synthesize controller;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions (NSDictionary *)launchOptions {
self.controller = [[QuizViewController alloc] init] autorelease];
[window addSubview:[vc view]];
[window makeKeyAndVisible];
return YES;
}
- (void)dealloc {
....
[controller release]; controller = nil;
....
}
The views/windows do retain their child views, the view controllers retain their views, but the views don't retain their controllers. It's a "one-way" relationship, a clear has-a. This also comes in handy to prevent retain cycles.
You probably want to save the controller in an ivar in the class you alloc/init it, and release it in dealloc or when you pull the view from screen.
View controllers often get retained by other view controllers, i.e. when you push them onto a navigation stack, or put them in tabs.
If you don't mind dropping support for iOS 3.0/3.1/3.2, you can use the UIWindow.rootViewController property:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions (NSDictionary *)launchOptions {
UIViewController *vc = [[[QuizViewController alloc] init] autorelease];
window.rootViewController = vc;
[window makeKeyAndVisible];
return YES;
}

Linking Model to Controller in simple application?

I am just looking at ways to access a simple model object (in the MVC sense) from my controller. Right now I am creating the model in the applicationDelegate, and passing it to the controller when I create the controller.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Setup Model
DataModel *tempDataModel = [[DataModel alloc] init];
[self setDataModel:tempDataModel];
[tempDataModel release];
// Setup Controllers
Controller *rootController = [[Controller alloc] initWithModel:[self dataModel]];
UINavigationController *tempNavController = [[UINavigationController alloc] initWithRootViewController:rootController];
[self setNavController:tempNavController];
[rootController release];
[tempNavController release];
[window addSubview:[[self navController] view]];
[window makeKeyAndVisible];
return YES;
}
inside the controller I have:
#property (nonatomic, retain)DataModel *dataModel;
and:
- (id)initWithModel:(id)newModel {
self = [super init];
if(self) {
NSLog(#"%s", __PRETTY_FUNCTION__);
dataModel = [newModel retain];
}
return self;
}
- (void)dealloc {
NSLog(#"%s", __PRETTY_FUNCTION__);
[dataModel release];
[super dealloc];
}
This works fine, but I am just curious if this is ok in terms of MVC and good design. In previous apps I have:
Used a shared instance (Singleton)
Created the model from inside the controller.
Any comments would me much appreciated:
I think this is perfectly good design. The controller is allowed to manipulate the model, so needs a reference to this. I think your current way of injecting the Model instance is better than a singleton approach.