填充的nsmutable数组返回空数组异常

时间:2013-05-03 21:25:52

标签: iphone objective-c uitableview nsmutablearray

我有一张桌子,我检查/取消选中细胞..我不知道为什么,但有时我会得到以下异常:

'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array'

我试图重现那个错误,但它真的不是同时发生..我会把我的整个viewcontroller代码放在这里,也许你可以看到问题。我正在寻找好几天......

#import "EventMembersViewController.h"
#import "CostumContactCell.h"
#import "ChatViewController.h"
#import "ADVTheme.h"
#import "RCSwitchOnOff.h"
#import "ADVProgressBar.h"
#import "UtilitieHandler.h"
#import "ContactDTO.h"
#import "User.h"
#import "Event.h"
#import "DCConnector.h"
#import "LastEventsViewController.h"

#import <QuartzCore/QuartzCore.h>
#import <UIKit/UIKit.h>


#define UUID_USER_DEFAULTS_KEY @"UUID"
#define NAME_USER_DEFAULTS_KEY @"UserName"
#define UPNumber_USER_DEFAULTS_KEY @"UPNumber"

#define kCellImageViewTag           1000

@interface EventMembersViewController (){
    NSMutableArray *totalContacts;
    NSMutableArray *filteredContacts;
    BOOL isFiltered;
    UtilitieHandler *io;
    UIImage *unselected, *selected;
    NSMutableArray *selectedArray;
    int counter;
    User *appUser;
    DCConnector *dccon;
}

@end

@implementation EventMembersViewController

@synthesize eventDTO, contactsTable;

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

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    [ADVThemeManager customizeView:self.view];


    [self initViewData];

}

- (void) initViewData{
    self.searchBar.delegate = self;
    self.contactsTable.delegate = self;

    self.contactsTable.dataSource = self;

    totalContacts = [[NSMutableArray alloc]init];

    dccon = [DCConnector new];
    totalContacts = [dccon getContacts];

    // get appUser
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *phoneNumber;
    if ([defaults objectForKey:UPNumber_USER_DEFAULTS_KEY] != nil) {
        phoneNumber = [defaults objectForKey:UPNumber_USER_DEFAULTS_KEY];
        appUser = [dccon getUserByPhonenumber:phoneNumber];

        NSLog(@"displayName: %@", appUser.displayName);
    }

    // load images of checked/unchecked cells
    selected = [UIImage imageNamed:@"checkmark.png"];
    unselected = [UIImage imageNamed:@"uncheckmark.png"];

    //populate selectedArray
    [self populateSelectedArray];

    // Set member counter
    counter = 0;

    UILabel *labelTitle = [[UILabel alloc] initWithFrame:CGRectZero];
    labelTitle.backgroundColor = [UIColor clearColor];
    labelTitle.textColor = [UIColor colorWithRed:0.98f green:0.96f blue:0.94f alpha:1.00f];
    labelTitle.font = [UIFont fontWithName:@"OpenSans-Semibold" size:16];
    labelTitle.text = @"Contacts 0/50";
    [labelTitle sizeToFit];
    UIView *viewTitle = [[UIView alloc] initWithFrame:labelTitle.bounds];
    CGRect frameLbl = labelTitle.bounds;
    viewTitle.frame = frameLbl;
    [viewTitle addSubview:labelTitle];
    [self.navigationItem setTitleView:viewTitle];


    UIBarButtonItem *newEventToggleView = [[UIBarButtonItem alloc]initWithTitle:@"Create" style:UIBarButtonItemStylePlain target:self action:@selector(initNextEventsOverview)];
    [newEventToggleView setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIFont fontWithName:@"OpenSans-Semibold" size:12.0], UITextAttributeFont,nil] forState:UIControlStateNormal];

    [self.navigationItem setRightBarButtonItem:newEventToggleView];

    self.contactsTable.backgroundColor = [UIColor clearColor];
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background-tbl"]];
}

- (void) initNextEventsOverview{
    NSMutableArray *selectedContacts = [[NSMutableArray alloc]init];


    if (counter == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Please select at least one contact!"
                                                        message:@""
                                                       delegate:self
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles: nil];
        [alert show];
    }else{

        NSLog(@"LENGTH %d", [selectedArray count]);

        for (int i = 0; i < [selectedArray count]; i++) {
            NSLog(@"Loop %d", i);

            BOOL selected_b = [[selectedArray objectAtIndex:i] boolValue];

            NSLog(@"Bool of Loop %d", selected_b);

            if (selected_b) {
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                CostumContactCell *cell = [contactsTable cellForRowAtIndexPath:indexPath];

                ContactDTO *member = [ContactDTO new];
                member = cell.contactObject;
                User *invitedUser = [dccon getUserByPhonenumber:member.phoneNumber];
                [selectedContacts addObject:invitedUser];
            }
        }

        self.eventDTO.invitedMembers = selectedContacts;

        // Create Event and push to overview list
        if ([dccon createEvent:self.eventDTO :appUser]) {
            LastEventsViewController *recentEvent = [[LastEventsViewController alloc]init];
            recentEvent.navigationItem.hidesBackButton = YES;
            [[self navigationController]pushViewController:recentEvent animated:YES];
        }
    }

}


- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    if (searchText.length == 0) {
        isFiltered = NO;
    }else{
        isFiltered = YES;
        filteredContacts = [[NSMutableArray alloc]init];

        for (ContactDTO *str in totalContacts) {
            NSRange stringRange = [str.fullName rangeOfString:searchText options:NSCaseInsensitiveSearch];
            if (stringRange.location != NSNotFound) {
                [filteredContacts addObject:str];
            }
        }
    }
    [self.contactsTable reloadData];
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self.searchBar resignFirstResponder];
}

// table iew delegate methodes..
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    if (isFiltered) {
        return [filteredContacts count];
    }
    return [totalContacts count];
}

- (void)populateSelectedArray
{
    NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:[totalContacts count]];
    for (int i=0; i < [totalContacts count]; i++)
        [array addObject:[NSNumber numberWithBool:NO]];
    selectedArray = array;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [self.contactsTable deselectRowAtIndexPath:indexPath animated:NO];

        BOOL selected_b = [[selectedArray objectAtIndex:[indexPath row]] boolValue];
        if (!selected_b) {
            if (counter < 51) {
                [selectedArray replaceObjectAtIndex:[indexPath row] withObject:[NSNumber numberWithBool:YES]];
                counter = counter + 1;
            }else{
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Maximal invites reached!"
                                                                message:@""
                                                               delegate:self
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles: nil];
                [alert show];
            }
         }else{
             [selectedArray replaceObjectAtIndex:[indexPath row] withObject:[NSNumber numberWithBool:NO]];
             counter = counter - 1;
         }

    [self updateViewTitle:counter];
    [self.contactsTable reloadData];
}

-(void)updateViewTitle:(int)count{

    UILabel *labelTitle = [[UILabel alloc] initWithFrame:CGRectZero];
    labelTitle.backgroundColor = [UIColor clearColor];
    labelTitle.textColor = [UIColor colorWithRed:0.98f green:0.96f blue:0.94f alpha:1.00f];
    labelTitle.font = [UIFont fontWithName:@"OpenSans-Semibold" size:16];
    labelTitle.text = [NSString stringWithFormat:@"Contact %d/50", count];
    [labelTitle sizeToFit];
    UIView *viewTitle = [[UIView alloc] initWithFrame:labelTitle.bounds];
    CGRect frameLbl = labelTitle.bounds;
    viewTitle.frame = frameLbl;
    [viewTitle addSubview:labelTitle];
    [self.navigationItem setTitleView:viewTitle];
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *CellIdentifier = @"Cell";
    CostumContactCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = (CostumContactCell *)[CostumContactCell cellFromNibNamed:@"CostumContactCell"];

        cell.contactImage.layer.cornerRadius = 5;
        cell.contactImage.layer.masksToBounds = YES;
        UIImageView *av = [[UIImageView alloc] initWithFrame:CGRectMake(20, 20, 277, 58)];
        av.backgroundColor = [UIColor clearColor];
        av.opaque = NO;
        av.image = [UIImage imageNamed:@"list-element.png"];
        cell.backgroundView = av;

        UIImageView *imageView = [[UIImageView alloc] initWithImage:unselected];
        imageView.frame = CGRectMake(cell.frame.size.width - 40.0, 15.0 , 25.0, 25.0);
        [cell.contentView addSubview:imageView];
        imageView.tag = kCellImageViewTag;
    }

    UIImageView *imageView = (UIImageView *)[cell.contentView viewWithTag:kCellImageViewTag];
    NSNumber *selectedNS = [selectedArray objectAtIndex:[indexPath row]];
    imageView.image = ([selectedNS boolValue]) ? selected : unselected;
    [UIView commitAnimations];

    if (!isFiltered) {
        ContactDTO *contact = [totalContacts objectAtIndex:indexPath.row];
        cell.contactName.text = contact.fullName;
        cell.contactStatus.text = contact.status;
        cell.contactObject = contact;
    } else {
        ContactDTO *contact = [filteredContacts objectAtIndex:indexPath.row];
        cell.contactName.text = contact.fullName;
        cell.contactStatus.text = contact.status;
        cell.contactObject = contact;
    }

    return cell;
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

它在那个循环中崩溃:

- (void) initNextEventsOverview{
    NSMutableArray *selectedContacts = [[NSMutableArray alloc]init];


    if (counter == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Please select at least one contact!"
                                                        message:@""
                                                       delegate:self
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles: nil];
        [alert show];
    }else{

        NSLog(@"LENGTH %d", [selectedArray count]);

        for (int i = 0; i < [selectedArray count]; i++) {
            NSLog(@"Loop %d", i);

            BOOL selected_b = [[selectedArray objectAtIndex:i] boolValue];

            NSLog(@"Bool of Loop %d", selected_b);

            if (selected_b) {
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                CostumContactCell *cell = [contactsTable cellForRowAtIndexPath:indexPath];

                ContactDTO *member = [ContactDTO new];
                member = cell.contactObject;
                User *invitedUser = [dccon getUserByPhonenumber:member.phoneNumber];
                [selectedContacts addObject:invitedUser];
            }
        }

        self.eventDTO.invitedMembers = selectedContacts;

        // Create Event and push to overview list
        if ([dccon createEvent:self.eventDTO :appUser]) {
            LastEventsViewController *recentEvent = [[LastEventsViewController alloc]init];
            recentEvent.navigationItem.hidesBackButton = YES;
            [[self navigationController]pushViewController:recentEvent animated:YES];
        }
    }

}

我很感激任何提示......

1 个答案:

答案 0 :(得分:0)

错误表明导致异常的数组是 NOT 一个可变数组,而是一个常规的NSArray,它排除了所有可变数组,包括selectedArray。 我猜这个错误与这些行有关

 if (selected_b) {
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                CostumContactCell *cell = [contactsTable cellForRowAtIndexPath:indexPath];

                ContactDTO *member = [ContactDTO new];
                member = cell.contactObject;
                User *invitedUser = [dccon getUserByPhonenumber:member.phoneNumber];
                [selectedContacts addObject:invitedUser];
            }

特别是那一行:

User *invitedUser = [dccon getUserByPhonenumber:member.phoneNumber];

您可以添加一个异常断点,如图here所示,以帮助您更好地调试代码。