繁体   English   中英

“尝试将第0行插入第0部分,但更新后第0部分只有0行”错误

[英]“Attempt to insert row 0 into section 0, but there are only 0 rows in section 0 after the update” Error

我有一个应用程序,从他们的联系人列表中选择一个人,并采取他们的名字,姓氏和电子邮件。 然后它将名字保存到nsmutablearray并将其放入uitableview单元格中。 一旦在模拟器中选择了联系人,我的问题就出现了。

码:

。H:

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

@interface FirstViewController : UIViewController <    ABPeoplePickerNavigationControllerDelegate, UITableViewDelegate, UITableViewDataSource>

- (IBAction)showPicker:(id)sender;

@property (weak, nonatomic) IBOutlet NSString *firstName;

@property (weak, nonatomic) IBOutlet NSString *email;

@property (weak, nonatomic) IBOutlet NSString *lastName;


@property (weak, nonatomic) IBOutlet UITableView *myTableView;

@property (strong, nonatomic) NSMutableArray *contacts;

@end

.M:

#import "FirstViewController.h"

@interface FirstViewController ()

@end

@implementation FirstViewController

@synthesize firstName;

@synthesize email;

@synthesize lastName;

@synthesize contacts;

@synthesize myTableView;


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    contacts = [[NSMutableArray alloc]initWithObjects:nil];
}

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

#pragma mark - UITableView Datasource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
} 

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return contacts.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath  *)indexPath
{
    static NSString *cellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault  reuseIdentifier:cellIdentifier];

    }

    cell.textLabel.text = [contacts objectAtIndex:indexPath.row];

    return cell;
}

- (IBAction)showPicker:(id)sender {

    ABPeoplePickerNavigationController *picker =
    [[ABPeoplePickerNavigationController alloc] init];
    picker.peoplePickerDelegate = self;

    [self presentModalViewController:picker animated:YES];
}

- (void)peoplePickerNavigationControllerDidCancel:
(ABPeoplePickerNavigationController *)peoplePicker
{
    [self dismissModalViewControllerAnimated:YES];
}


- (BOOL)peoplePickerNavigationController:
(ABPeoplePickerNavigationController *)peoplePicker
      shouldContinueAfterSelectingPerson:(ABRecordRef)person {

    [self displayPerson:person];
    [self dismissModalViewControllerAnimated:YES];

    return NO;
}

- (BOOL)peoplePickerNavigationController:
(ABPeoplePickerNavigationController *)peoplePicker
      shouldContinueAfterSelectingPerson:(ABRecordRef)person
                                property:(ABPropertyID)property
                              identifier:(ABMultiValueIdentifier)identifier
{





    return NO;

}


- (void)displayPerson:(ABRecordRef)person
{
    NSString* name = (__bridge_transfer NSString*)ABRecordCopyValue(person,
                                                                    kABPersonFirstNameProperty);
    self.firstName = name;

    NSString* last = (__bridge_transfer NSString*)ABRecordCopyValue(person,
                                                                    kABPersonLastNameProperty);
    self.lastName = last;


    ABMultiValueRef  emails = ABRecordCopyValue(person, kABPersonEmailProperty);
    NSString *emailId = (__bridge NSString *)ABMultiValueCopyValueAtIndex(emails, 0);//0     for "Home Email" and 1 for "Work Email".

    self.email = emailId;

    if (!(contacts))
    {

        contacts = [[NSMutableArray alloc]init];

    }

    [contacts insertObject:firstName atIndex:0];

    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

    [self.myTableView insertRowsAtIndexPaths:@[indexPath]  withRowAnimation:UITableViewRowAnimationAutomatic];
}




@end

UITableView必须始终与数据源保持同步。 如果数据源可以在后台线程中更改,则必须特别小心。

当某些内容添加到数据源时,请尽快调用beginUpdate / insert / endUpdate。 您不必担心缓存这些,UITableView会在确定有足够的CPU时间和资源时缓存要执行的更改。

调用endUpdates时,UITable将再次询问dataSource的节和行数。 如果直接来自dataSource的节和行的数量,则数字节和行,加上插入,减去删除必须等于numberOfSections和numberOfRowsInSection的结束调用返回的数字。

最后一个提示:避免混合调用'reloadData'和beginUpdate / endUpdate对。 使用其中一个,而不是两个。

我遇到了同样的问题。 你所要做的就是改变

[self.myTableView insertRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationAutomatic];`

 [self.myTableView beginUpdates];

 [self.myTableView insertRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationAutomatic];

 [self.myTableView endUpdates];

来自UITableView文档

beginUpdates

Begin a series of method calls that insert, delete, or select rows and sections of the receiver.

当您使用beginUpdates ,您必须调用endUpdates而不是reloadData

您可以访问https://developer.apple.com/library/ios/documentation/uikit/reference/UITableView_Class/Reference/Reference.html以获取更多UITableView信息。

希望这可以帮助!

以上关于实现-tableView:numberOfRowsInSection:的注释是正确的。 断言正在检查返回的值,期望它会增加。

但是,由于您没有在UITableView上设置dataSource ,因此调用(或不调用)一个不存在且获得0

您需要将myTableView.dataSource和(因为您也实现委托协议) myTableView.delegateself

你也可能需要类似的东西

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
    ...
}

除非您在其他地方注册,否则您的故事板上会有一个“原型单元”,其中包含您的代码所要求的标识符"Cell"

我发现当我在View Controller中放置一个表视图时,通常会发生此问题。 如果您正在使用UITableViewController跳转到3。

这些步骤可能有所帮助

1:在View Controller .h文件中,确保添加以下内容:

@interface YourViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>

2:接下来通过ctrl +拖动到你的.h类为你的表视图创建一个IBOutlet。 它应该看起来像:

@property (weak, nonatomic) IBOutlet UITableView *tableView;

3:下一步是按住Ctrl键并拖动到View Controllers图标(见图)

在此输入图像描述

您需要选择两次:

- delegate
- datasource

最后,在.m文件中,您应该使用以下方法:

- (void) viewWillAppear:(BOOL)animated{
    //[self.tableView beginUpdates];
    //[self.tableView endUpdates];

    [self.tableView reloadData];
}

您可以使用beginUpDates / endUpdates或reloadData,但Apple文档建议使用reloadData。

完成后,您的表应该可以正常工作。

您需要维护联系人数组的计数并相应地增加。
在创建indexPath时,您需要设置适当的indexPathForRow:和section count(如果需要)。

- (void)displayPerson:(ABRecordRef)person
{

  ..........

[contacts insertObject:firstName atIndex:0];

NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; // you cant do this increment appropriately

 .........
}

请检查您的tableview数据源和委托方法。 您可能正在将空数组传递给数据源方法。 并且不要忘记在获取数据后重新加载tableview。

我知道这是愚蠢的 - 我得到了同样的错误,因为我忘了设置委托和dataSource。

因此,在插入行并执行tableView.endUpdates() ,tableView认为它必须有一些行 - 但由于未链接的dataSource ,它没有。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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