1

Sorry, this could be a simple fix, as I am new to iPhone Development.

In my Delegate, after pressing the create profile button, the create profile view is pushed:

-(void) createProfile_clicked:(id)sender
 {


   AddNewProfile *create = [[AddNewProfile alloc] init]; 


   [self.window addSubview:create.view];

  [self invisibleCreateProfileBar];


    AddNewProfile *controller = [[AddNewProfile alloc] initWithNibName:@"AddNewProfile" bundle:[NSBundle mainBundle]];
   [self.navigationController pushViewController:controller animated:YES ];

    currentController=controller;
}

Then in the AddNewProfile.m:

- (IBAction)backgroundTap:(id)sender {
if([nameField isFirstResponder]){
    [nameField resignFirstResponder];
}

if([ageField isFirstResponder]){
    [ageField resignFirstResponder];
}

if([doctorNameField isFirstResponder]){
    [doctorNameField isFirstResponder];
}

if([doctorNumberField isFirstResponder]){
    [doctorNumberField resignFirstResponder];
}
   }

This leads to a exc_bad_access error every time the FirstResponder is ever messed with, with any of my controls. I can select a control(text box), but once I click out of one, it crashes.

Any help would be greatly appreciated.

Could it have to do with retaining any fields? Do you guys need any more code? Sorry I am just really new to all of this. :/


EDIT:

ALL CODE FROM THE TWO FILES

appdelegate.m

#import "BIDDailyMedsAppDelegate.h"
#import "RootViewController.h"
#import "ProfileHomeViewController.h"
#import "AddNewProfile.h"
#import "BIDMedicationEditViewController.h"
#import "BIDMedicationListViewController.h"

@implementation BIDDailyMedsAppDelegate

@synthesize window = _window;
@synthesize navigationController;

UIToolbar *toolbar;

NSString *currentProfileName = @"";

@synthesize managedObjectContext = __managedObjectContext;
@synthesize managedObjectModel = __managedObjectModel;
@synthesize persistentStoreCoordinator = __persistentStoreCoordinator;

AddNewProfile *currentController;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    sleep(5);

    UIViewController *rootController = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:nil];

    navigationController = [[UINavigationController alloc] initWithRootViewController:rootController];

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];



    [self.window addSubview:navigationController.view];


    //Initialize the toolbar 
    toolbar = [[UIToolbar alloc] init]; 
    toolbar.barStyle = UIBarStyleDefault;

    //Set the toolbar to fit the width of the app. 
    [toolbar sizeToFit];

    //Caclulate the height of the toolbar 
    CGFloat toolbarHeight = [toolbar frame].size.height;

    //Get the bounds of the parent view 
    CGRect rootViewBounds = self.navigationController.view.bounds;

    //Get the height of the parent view. 
    CGFloat rootViewHeight = CGRectGetHeight(rootViewBounds);

    //Get the width of the parent view, 
    CGFloat rootViewWidth = CGRectGetWidth(rootViewBounds);

    //Create a rectangle for the toolbar 
    CGRect rectArea = CGRectMake(0, rootViewHeight - toolbarHeight, rootViewWidth, toolbarHeight);

    //Reposition and resize the receiver 
    [toolbar setFrame:rectArea];

    //Create a button 
    UIBarButtonItem *createButton = [[UIBarButtonItem alloc] initWithTitle:@"Create Profile" style:UIBarButtonItemStyleBordered target:self action:@selector( createProfile_clicked:)];

    [toolbar setItems:[NSArray arrayWithObjects:createButton,nil]];

    //Add the toolbar as a subview to the navigation controller. [self.navigationController.view addSubview:toolbar];

    [self.window addSubview:toolbar];
    //[[self tableView] reloadData];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

-(NSString*) getCurrentName{
    return currentProfileName;
}
-(void) setCurrentName:(NSString*)name{
    currentProfileName=name;
}

-(void) createProfile_clicked:(id)sender {

    //[self.navigationController popViewControllerAnimated:YES];
    //[toolbar removeFromSuperview];
    AddNewProfile *create = [[AddNewProfile alloc] init]; 

    //[ removeFromSuperview];
    [self.window addSubview:create.view];
    //[toolbar removeFromSuperview];
    //[toolbar setOpaque:true];
    [self invisibleCreateProfileBar];

    //[creater pushViewController: animated:YES];

    AddNewProfile *controller = [[AddNewProfile alloc] initWithNibName:@"AddNewProfile" bundle:[NSBundle mainBundle]];
    [ self.navigationController pushViewController:controller animated:YES ];
    //[self.navigationController.view addSubview:controller];

    //[self.navigationController presentModalViewController:controller animated:YES];
    //currentController=controller;
    //[currentController.nameField becomeFirstResponder];

}

-(void) clearCreateProfileFields{

    if([currentController.nameField isFirstResponder]){
        [currentController.nameField resignFirstResponder];
    }

    if([currentController.ageField isFirstResponder]){
        [currentController.ageField resignFirstResponder];
    }

    if([currentController.doctorNameField isFirstResponder]){
        [currentController.doctorNameField isFirstResponder];
    }

    if([currentController.doctorNumberField isFirstResponder]){
        [currentController.doctorNumberField resignFirstResponder];
    }
    //[self becomeFirstResponder];
}

-(void) addMedication_clicked:(id)sender{
    //BIDMedicationEditViewController *editMed = [[BIDMedicationEditViewController alloc] init];

    //[self.window addSubview:editMed.view];
    //[self.navigationController pushViewController:self.profileHomeController animated:YES];

    BIDMedicationEditViewController *controller = [[BIDMedicationEditViewController alloc] initWithNibName:@"MedicationEditView" bundle:[NSBundle mainBundle]];
    [self.navigationController pushViewController:controller animated:YES];

}

-(void) medicationMenu_clicked:(id)sender{
    //BIDMedicationListViewController *viewMed = [[BIDMedicationListViewController alloc] init];
    //[self.window addSubview:viewMed.view];
    //[self.navigationController pushViewController: animated:<#(BOOL)#>];


    BIDMedicationListViewController *controller = [[BIDMedicationListViewController alloc] initWithNibName:@"MedicationListView" bundle:[NSBundle mainBundle]];
    [self.navigationController pushViewController:controller animated:YES];
    //[controller release];
}

-(void) invisibleCreateProfileBar
{
    //[toolbar removeFromSuperview];
    [toolbar setHidden:true];
}

-(void) visibleCreateProfileBar
{
    [toolbar setHidden:false];
}

- (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, this method is called instead of applicationWillTerminate: when the user quits.
     */
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     Called as part of the 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
{
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    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();
        } 
    }
}

#pragma mark - Core Data stack

/**
 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 *)managedObjectContext
{
    if (__managedObjectContext != nil)
    {
        return __managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil)
    {
        __managedObjectContext = [[NSManagedObjectContext alloc] init];
        [__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 *)managedObjectModel
{
    if (__managedObjectModel != nil)
    {
        return __managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"DailyMeds_withCoreData" 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 *)persistentStoreCoordinator
{
    if (__persistentStoreCoordinator != nil)
    {
        return __persistentStoreCoordinator;
    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"DailyMeds_withCoreData.sqlite"];

    NSError *error = nil;
    __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self 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: 
         [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

         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;
}

#pragma mark - Application's Documents directory

/**
 Returns the URL to the application's Documents directory.
 */
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

@end

Here is the create profile.m file:

#import "AddNewProfile.h"
#import "BIDDailyMedsAppDelegate.h"
#import "BIDDailyMedsAppDelegate.h"

@implementation AddNewProfile
@synthesize nameField;
@synthesize ageField;
@synthesize doctorNameField;
@synthesize doctorNumberField;
@synthesize saveButton;
@synthesize sexField;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];


    //[nameField becomeFirstResponder];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [self setNameField:nil];
    [self setAgeField:nil];
    [self setDoctorNameField:nil];
    [self setDoctorNumberField:nil];
    [self setSaveButton:nil];
    [self setSexField:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction)pressSave:(id)sender {

    BIDDailyMedsAppDelegate *appDelegate = 
    [[UIApplication sharedApplication] delegate];

    NSManagedObjectContext *context = 
    [appDelegate managedObjectContext];
    NSManagedObject *newContact;
    newContact = [NSEntityDescription
                  insertNewObjectForEntityForName:@"Profiles"
                  inManagedObjectContext:context];
    [newContact setValue:self.nameField.text forKey:@"name"];
    [newContact setValue:self.ageField.text forKey:@"age"];
    if(self.sexField.selected==0){
        [newContact setValue:@"YES" forKey:@"male"];
    }else{
        [newContact setValue:@"NO" forKey:@"male"];
    }
    [newContact setValue:self.doctorNameField.text forKey:@"doctorName"];
    [newContact setValue:self.doctorNumberField.text forKey:@"doctorPhone"];

    NSError *error;
    [context save:&error];

    //Pop view off stack
    // locally store the navigation controller since
    // self.navigationController will be nil once we are popped
    UINavigationController *navController = self.navigationController;

    // Pop this controller and replace with another
    [navController popToRootViewControllerAnimated:YES];

    //UIViewController *rootController = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:nil];

    //[navController pushViewController:rootController animated:YES];
}

- (IBAction)backgroundTap:(id)sender {
    //AppDelegate = [[UIApplication sharedApplication] delegate];
    //[AppDelegate clearCreateProfileFields];

    //UITextField *currentTextField=sender;
    //[currentTextField resignFirstResponder];

    [self.view endEditing: YES];

}
@end
gkres121
  • 11
  • 3
  • Put breakpoints and let us know exactly at which line it gives EXC_BAD_ACCESS. Otherwise you will get randomly assumed answers from others.. – rohan-patel Apr 12 '12 at 05:55
  • So I put breakpoints at the beginning of every function, including bagroundTap, which it doesn't even hit. It must get the error somewhere else, but no where any of the breakpoints are in that file. Any suggestions? – gkres121 Apr 13 '12 at 03:22

4 Answers4

2

It is usually difficult to work out where a EXC_BAD_ACCESS happens without enabling NSZombiesEnabled. Try turning it on and testing it again.

See How can I set NSZombiesEnabled in XCode4? on how to turn it on.

Community
  • 1
  • 1
gak
  • 32,061
  • 28
  • 119
  • 154
0

TRy this

- (IBAction)backgroundTap:(id)sender {
            [self.view endEditing:YES];
        }

may this work for u.

 - (IBAction)backgroundTap:(id)sender {
    [sender resignFirstResponder];
    }

THere is no meaning in your code this

if([doctorNameField isFirstResponder]){
    [doctorNameField isFirstResponder];
}
gauravds
  • 2,931
  • 2
  • 28
  • 45
0

If you don't know which editing field is first responder, but want to resign it, you should use this call:

[self.view endEditing: NO];

From the Apple docs:

This method looks at the current view and its subview hierarchy for the text field that is currently the first responder. If it finds one, it asks that text field to resign as first responder. If the force parameter is set to YES, the text field is never even asked; it is forced to resign

Ashley Mills
  • 50,474
  • 16
  • 129
  • 160
  • - (IBAction)backgroundTap:(id)sender { [self.view endEditing: YES]; } Still getting the same error – gkres121 Apr 13 '12 at 01:56
  • 2012-04-12 22:10:24.611 DailyMeds_withCoreData[13061:fb03] -[__NSCFArray backgroundTap:]: unrecognized selector sent to instance 0x6ba0e80 2012-04-12 22:10:24.808 DailyMeds_withCoreData[13061:fb03] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray backgroundTap:]: unrecognized selector sent to instance 0x6ba0e80' Is my new problem (SIGABRT), any suggestions? – gkres121 Apr 13 '12 at 02:12
  • For some reason, now I'm back to getting EXC_BAD_ACCESS again. However, maybe that one time difference can give some insight into the real problem – gkres121 Apr 13 '12 at 02:17
0

Based on the new info you've provided, it looks like you may be releasing the reference to the view controller, which means the backgroundTap is being called against an unknown block of memory rather than on the VC. Depending on how the free'd memory is reused you may get a variety of errors - bad access the most likely but if the memory was reused for another object that is within scope for your app you may get the 'unrecognized selector' message instead.

Check whether you are calling 'release' on the 'currentController' var anywhere - or if it is declared as a 'retain' property, check that you aren't reassigning a value to it somewhere which would cause a release of the current reference. (since you are not assigning to currentController via a property reference, but directly to the ivar, a reassignment somewhere using the property reference would cause it to be released if it is declared as a retain property.

gamozzii
  • 3,911
  • 1
  • 30
  • 34
  • The currentController was a failed attempt at a workaround, to if cleaning the fields from the first responder from the delegate would be any better. I don't know why I thought that would help, I just was trying anything different at that point. I edited the original post to add all current code from those files. I'm sure there is very messy code, doing things that probably isn't best, but again, I'm learning as I go, and the resulting code is somewhat hodgepodge – gkres121 Apr 13 '12 at 03:08