1

抱歉,这可能是一个简单的修复,因为我是 iPhone 开发的新手。

在我的代表中,按下创建配置文件按钮后,创建配置文件视图被推送:

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

每次使用我的任何控件,FirstResponder 被弄乱时,这都会导致 exc_bad_access 错误。我可以选择一个控件(文本框),但是一旦我单击其中一个,它就会崩溃。

任何帮助将不胜感激。

是否与保留任何字段有关?你们还需要代码吗?对不起,我对这一切真的很陌生。:/


编辑:

两个文件中的所有代码

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
4

4 回答 4

2

EXC_BAD_ACCESS如果不启用,通常很难确定发生的位置NSZombiesEnabled。尝试将其打开并再次测试。

请参阅如何在 XCode4 中设置 NSZombiesEnabled?关于如何打开它。

于 2012-04-12T05:29:31.157 回答
0

尝试这个

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

愿这对你有用。

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

您的代码中没有任何意义

if([doctorNameField isFirstResponder]){
    [doctorNameField isFirstResponder];
}
于 2012-04-12T05:30:59.517 回答
0

如果您不知道哪个编辑字段是第一响应者,但想辞职,您应该使用此调用:

[self.view endEditing: NO];

来自苹果文档:

此方法查看当前视图及其子视图层次结构,以查找当前是第一响应者的文本字段。如果找到,它会要求该文本字段辞去第一响应者的职务。如果 force 参数设置为 YES,则永远不会询问文本字段;它被迫辞职

于 2012-04-12T16:16:51.333 回答
0

根据您提供的新信息,您似乎正在释放对视图控制器的引用,这意味着正在针对未知的内存块而不是在 VC 上调用 backgroundTap。根据释放内存的重用方式,您可能会遇到各种错误 - 最有可能是错误访问,但如果内存被重用于您的应用程序范围内的另一个对象,您可能会收到“无法识别的选择器”消息。

检查您是否在任何地方调用 'currentController' var 的 'release' - 或者如果它被声明为 'retain' 属性,请检查您是否没有在某处重新分配值,这会导致释放当前引用。(由于您不是通过属性引用分配给 currentController,而是直接分配给 ivar,因此如果将其声明为保留属性,则使用属性引用在某处重新分配将导致它被释放。

于 2012-04-13T02:48:32.240 回答