簡體   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