2013-05-03 25 views
0

我有一個表,我選中/取消細胞..我不知道爲什麼,但有時我得到以下異常:填充nsmutable陣列返回空數組例外

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

} 

我將不勝感激任何提示..

回答

0

的錯誤指示陣列引起例外是不是一個可變數組,但是一個常規的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,以幫助您調試代碼更好。

+0

你就是這樣!謝謝..我正在通過索引訪問一個對象,即使它不在那裏...我完全忘記了這個方法 – SaifDeen 2013-05-03 22:16:25