抱歉,这可能是一个简单的修复,因为我是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
这是create 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 :(得分:2)
通常很难找到EXC_BAD_ACCESS
未启用NSZombiesEnabled
的情况。尝试将其打开并再次测试。
请参阅How can I set NSZombiesEnabled in XCode4?了解如何打开它。
答案 1 :(得分:0)
试试这个
- (IBAction)backgroundTap:(id)sender {
[self.view endEditing:YES];
}
这可能对你有用。
- (IBAction)backgroundTap:(id)sender {
[sender resignFirstResponder];
}
这在你的代码中没有任何意义
if([doctorNameField isFirstResponder]){
[doctorNameField isFirstResponder];
}
答案 2 :(得分:0)
如果您不知道哪个编辑字段是第一响应者,但想要重新签名,则应使用此呼叫:
[self.view endEditing: NO];
来自Apple文档:
此方法查看当前视图及其子视图层次结构 当前第一个响应者的文本字段。如果找到一个, 它要求文本字段作为第一响应者辞职。如果力量 参数设置为YES,甚至不询问文本字段;它是 被迫辞职
答案 3 :(得分:0)
根据您提供的新信息,您可能正在释放对视图控制器的引用,这意味着正在针对未知的内存块而不是VC上调用backgroundTap。根据免费内存的重用方式,您可能会遇到各种错误 - 最不可能访问错误但如果内存被重用于应用程序范围内的其他对象,则可能会收到“无法识别的选择器”消息。
检查你是否在'currentController'var上调用'release' - 或者如果它被声明为'retain'属性,请检查你是否在某个地方重新分配值,这会导致释放目前的参考。 (因为你没有通过属性引用分配给currentController,而是直接分配给ivar,使用属性引用在某处重新分配会导致它被释放,如果它被声明为retain属性。