简体   繁体   中英

why am I getting NSRangeException in Xcode

I am trying to load a plist from my project, this was working until I accidentally deleted my plist. the plist has 5 arrays, with 2 elements apiece. I know that I the program is trying to access beyond the range of the array, but what I don't know is where this index is set? Here is the code that it bombs on: this code is executed twice successfully,then for some reason it tries to access it a third time and bombs on the first line,why?

It throws this exception:

NSRangeException -[_NSCFARRAY objectAtIndex] index(2) beyond bounds (2)

please help, this is for a final project due on Monday and now I feel like I have to start over again.

 NSString *nameOfAccount = [account objectAtIndex:indexPath.row];
 cell.textLabel.text = nameOfAccount;
 NSString *accountNumber = [number objectAtIndex:indexPath.row];
 cell.detailTextLabel.text = accountNumber;

Since you are displaying the data in same cell, you can include both name and number of account into a dictionary or a custom model object which will hold both info.

In your plist this might be the structure, array of dictionary objects

在此处输入图片说明

When you are displaying the info. For the dataSource create an array say accounts .

#define kAccountName @"Name"
#define kAccountNumber @"Number"

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"Accounts" ofType:@"plist"];
    self.accounts = [NSArray arrayWithContentsOfFile:filePath];

}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [self.accounts count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    NSDictionary *account = self.accounts[indexPath.row];

    cell.textLabel.text = account[kAccountName];
    cell.detailTextLabel.text = account[kAccountNumber];

    // Configure the cell...

    return cell;
}

Source code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM