2012-04-12 3 views
1

Извините, это может быть простое исправление, поскольку я новичок в разработке iPhone.EXC_BAD_ACCESS в iPhone Development

В моем делегатом, после нажатия кнопки создать профиль, создать вид профиля выталкивается:

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

Тогда в 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]; 
} 
    } 

Это приводит к EXC_BAD_ACCESS ошибки каждый время, с которым когда-либо сталкивался FirstResponder, с любым из моих элементов управления. Я могу выбрать элемент управления (текстовое поле), но как только я выхожу из одного, он сработает.

Любая помощь была бы принята с благодарностью.

Может ли это иметь место при сохранении любых полей? Вам больше нужен код? Извините, я просто совсем не знаком со всем этим. :/


EDIT:

ВСЕ КОД ИЗ ДВУХ ФАЙЛЫ

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 

Вот файл создать profile.m:

#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 
+0

Положите контрольные точки и сообщите нам об этом точно в какой строке он дает EXC_BAD_ACCESS. В противном случае вы получите случайно принятые ответы от других. –

+0

Поэтому я поставил точки останова в начале каждой функции, в том числе bagroundTap, в которую он даже не попал. Он должен получить ошибку где-то в другом месте, но нет, где какая-либо из точек останова находится в этом файле. Любые предложения? – gkres121

ответ

2

Обычно трудно работать где EXC_BAD_ACCESS происходит без включения NSZombiesEnabled. Попробуйте включить его и снова проверить.

См. How can I set NSZombiesEnabled in XCode4? о том, как включить его.

0

TRY это

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

может эта работа для и.

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

Там нет никакого смысла в вашем коде это

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

Извините, что это была опечатка, и у меня первоначально был ваш код, но затем изменил его, чтобы попробовать разные вещи. – gkres121

+0

try [self.view endEditing: YES]; – dayitv89

+0

yup сделал это тоже, я понял, что вы имели в виду ДА – gkres121

0

Если вы не знаете, какой редактирование поля первый ответчик, но хочу уйти в отставку, вы должны использовать этот вызов:

[self.view endEditing: NO]; 

Из документов Apple:

Этот метод Лоо ks в текущем представлении и иерархии его подкатегории для текстовое поле, которое в настоящее время является первым ответчиком. Если он найдет один, , он попросит, чтобы текстовое поле ушло в отставку в качестве первого ответчика. Если для параметра силы установлено значение YES, текстовое поле никогда не запрашивается; он вынужден уйти в отставку

+0

- (IBAction) backgroundTap: (id) отправитель { [self.view endEditing: YES]; } по-прежнему получать ту же ошибку – gkres121

+0

2012-04-12 22: 10: 24,611 DailyMeds_withCoreData [13061]: fb03 - [__ NSCFArray backgroundTap]: непризнанные селектор направлен например 0x6ba0e80 2012-04-12 22:10: 24.808 DailyMeds_withCoreData [13061: fb03] *** Завершение приложения из-за неперехваченного исключения «NSInvalidArgumentException», причина: '- [__ NSCFArray backgroundTap:]: непризнанный селектор, отправленный экземпляру 0x6ba0e80' Является ли моя новая проблема (SIGABRT), какие-либо предложения? – gkres121

+0

По какой-то причине я снова вернулся к EXC_BAD_ACCESS. Однако возможно, что одно различие во времени может дать некоторое представление о реальной проблеме. – gkres121

0

на основе новой информации вы при условии, похоже, вы можете выпустить ссылку на контроллер представления, что означает, что backgroundTap вызывается против неизвестного блока памяти, а чем на ВК.В зависимости от того, как повторно используется свободная память, вы можете получить множество ошибок - плохой доступ, скорее всего, но если память была повторно использована для другого объекта, который находится в пределах области действия для вашего приложения, вы можете получить сообщение «непризнанный селектор».

Проверьте, что вы вызываете «release» в переменной «currentController» где угодно - или если оно объявлено как свойство «сохранить», убедитесь, что вы не переназначаете значение для него где-нибудь, что приведет к выпуску текущая ссылка. (так как вы не назначаете currentController через ссылку на свойство, а прямо в ivar, переназначение где-нибудь с использованием ссылки на свойство приведет к ее освобождению, если оно объявлено как свойство сохранения.

+0

CurrentController был неудачной попыткой обходного пути, если бы очистка полей от первого ответчика от делегата была бы лучше. Я не знаю, почему я думал, что это поможет, я просто пытался что-то другое в этот момент. Я отредактировал исходное сообщение, чтобы добавить весь текущий код из этих файлов. Я уверен, что есть очень грязный код, делающий вещи, которые, вероятно, не самые лучшие, но опять же, я учусь, когда я иду, и получившийся код несколько мешает – gkres121