如何在其他类中编辑NSMutableArray

时间:2014-05-26 18:28:48

标签: ios objective-c nsmutablearray exc-bad-access

我在“AppDelegate.h”中有NSMutableArray

@property (strong, nonatomic) NSMutableArray *myArray;

和“AppDelegate.m”

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.myArray = [[NSMutableArray alloc] init];

    return YES;
}

在UITableViewController中,我在NSMutableArray中添加对象

- (IBAction)AddComment:(UIBarButtonItem *)sender
{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

    SectionObject *sectionObject = [[SectionObject alloc] init];

    sectionObject.id = (NSInteger*)appDelegate.myArray.count;
    sectionObject.name = [NSString stringWithFormat:@"New object %i",appDelegate.myArray.count];

    [appDelegate.myArray addObject:sectionObject];

    [self.tableView reloadData];
}

要编辑对象,我从数组控制器传递其他UITableViewController对象

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    UINavigationController *navController = segue.destinationViewController;
    ExerciseTableViewController *controller = (ExerciseTableViewController *)navController;

    controller.contactdb = [appDelegate.myArray objectAtIndex:[[self.tableView indexPathForSelectedRow] row]];
}

当我回去写

-(void)viewWillDisappear:(BOOL)animated {

    if ([self.navigationController.viewControllers indexOfObject:self] == NSNotFound) {

        self.contactdb.name = self.nameTextField.text;
    }

    [super viewWillDisappear:animated];
}

我收到错误'EXC_BAD_ACCESS'。如果我不编辑self.contactdb.name,我没有错误。如何在其他控制器中编辑对象?

1 个答案:

答案 0 :(得分:0)

你的if语句:

  if ([self.navigationController.viewControllers indexOfObject:self] == NSNotFound) 

基本上保证您的视图控制器已从导航堆栈中删除。这就是为什么在尝试从该视图控制器访问属性时出现EXC_BAD_ACCESS错误的原因。您应该将self.contactdb.name = self.nameTextField.text语句放在其他位置。