UITableview重新加载问题

时间:2010-12-22 12:12:26

标签: iphone objective-c uitableview

我已经完成了我的学校项目申请,但遇到了一个主要的“错误”。 这是一个帐户管理应用程序。图片:

alt text

这是我点击加号时的问题,我推动导航控制器加载另一个视图来处理类别的添加和删除。当我添加并返回上面的视图时,它不会更新。它只在我点击右边的按钮后更新,这是用于更改某些设置的另一个视图,然后返回到页面。我对viewWillAppear进行了一些研究,但我仍然对它无法正常工作的原因感到困惑。

当我删除一个类别时,这个问题也影响了我的程序,并返回到该视图,它崩溃因为视图没有成功重新加载。删除并返回视图时,我会收到此错误。 “ *由于未捕获的异常'NSRangeException'终止应用程序,原因:'* - [NSMutableArray objectAtIndex:]:索引4超出边界[0 .. 3]'”。


[编辑]

表格视图代码:

@class LoginViewController;

@implementation CategoryTableViewController
@synthesize categoryTableViewController;
@synthesize categoryArray;
@synthesize accountsTableViewController;
@synthesize editAccountTable;
@synthesize window;

CategoryMgmtTableController *categoryMgmtTableController;
ChangePasswordView *changePasswordView;

- (void) save_Clicked:(id)sender {
/*
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Category Management" 
                                                message:@"Load category management table view"
                                               delegate:self 
                                      cancelButtonTitle: @"OK" 
                                      otherButtonTitles:nil];
[alert show];
[alert release];
*/
KeyCryptAppAppDelegate *appDelegate = (KeyCryptAppAppDelegate *)[[UIApplication sharedApplication] delegate];
categoryMgmtTableController = [[CategoryMgmtTableController alloc]initWithNibName:@"CategoryMgmtTable" bundle:nil]; 
[appDelegate.categoryNavController pushViewController:categoryMgmtTableController animated:YES];



}
- (void) change_Clicked:(id)sender {

 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Change Password" 
 message:@"Change password View"
 delegate:self 
 cancelButtonTitle: @"OK" 
 otherButtonTitles:nil];
 [alert show];
 [alert release];

KeyCryptAppAppDelegate *appDelegate = (KeyCryptAppAppDelegate *)[[UIApplication sharedApplication] delegate];
changePasswordView = [[ChangePasswordView alloc]initWithNibName:@"ChangePasswordView" bundle:nil]; 
[appDelegate.categoryNavController pushViewController:changePasswordView animated:YES];


/*
KeyCryptAppAppDelegate *appDelegate = (KeyCryptAppAppDelegate *)[[UIApplication sharedApplication] delegate];
categoryMgmtTableController = [[CategoryMgmtTableController alloc]initWithNibName:@"CategoryMgmtTable" bundle:nil]; 
[appDelegate.categoryNavController pushViewController:categoryMgmtTableController animated:YES];
*/


}
#pragma mark -
#pragma mark Initialization

/*
- (id)initWithStyle:(UITableViewStyle)style {
// Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
if ((self = [super initWithStyle:style])) {
}
return self;
}
*/



-(void) initializeCategoryArray {

sqlite3 *db= [KeyCryptAppAppDelegate getNewDBConnection];
KeyCryptAppAppDelegate *appDelegate = (KeyCryptAppAppDelegate *)[[UIApplication sharedApplication] delegate];

const char *sql = [[NSString stringWithFormat:(@"Select Category from Categories;")]cString];

const char *cmd = [[NSString stringWithFormat:@"pragma key = '%@' ", appDelegate.pragmaKey]cString];
sqlite3_stmt *compiledStatement;

sqlite3_exec(db, cmd, NULL, NULL, NULL);

if (sqlite3_prepare_v2(db, sql, -1, &compiledStatement, NULL)==SQLITE_OK)
{
    while(sqlite3_step(compiledStatement) == SQLITE_ROW)
        [categoryArray addObject:[NSString stringWithUTF8String:(char*) sqlite3_column_text(compiledStatement, 0)]];

}
else {
    NSAssert1(0,@"Error preparing statement", sqlite3_errmsg(db));
}
sqlite3_finalize(compiledStatement);
}



#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {

// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
[super viewDidLoad];
}



- (void)viewWillAppear:(BOOL)animated {

self.title = NSLocalizedString(@"Categories",@"Types of Categories");
categoryArray = [[NSMutableArray alloc]init];
[self initializeCategoryArray];

self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
                                           initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                                           target:self action:@selector(save_Clicked:)] autorelease];

self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]
                                          initWithBarButtonSystemItem:UIBarButtonSystemItemAction
                                          target:self action:@selector(change_Clicked:)] autorelease];

[super viewWillAppear:animated];
}


- (void)viewDidAppear:(BOOL)animated {
NSLog (@"view did appear");
[super viewDidAppear:animated];
}


- (void)viewWillDisappear:(BOOL)animated {

NSLog (@"view will disappear");
[super viewWillDisappear:animated];
}


- (void)viewDidDisappear:(BOOL)animated {
[categoryTableView reloadData];
NSLog (@"view did disappear");
[super viewDidDisappear:animated];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#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.categoryArray count];
}


// Customize the appearance of table view cells.
- (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] autorelease];
}

// Configure the cell...
NSUInteger row = [indexPath row];
cell.text = [categoryArray objectAtIndex:row];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

if (editingStyle == UITableViewCellEditingStyleDelete) {
    // Delete the row from the data source
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
}   
else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *selectedCategory = [categoryArray objectAtIndex:[indexPath row]]; 

NSLog (@"AccountsTableView.xib is called.");
if ([categoryArray containsObject: selectedCategory])
{
    if (self.accountsTableViewController == nil)
    {
        AccountsTableViewController *aAccountsView = [[AccountsTableViewController alloc]initWithNibName:@"AccountsTableView"bundle:nil];
        self.accountsTableViewController =aAccountsView;
        [aAccountsView release];
    }

    NSInteger row =[indexPath row];
    accountsTableViewController.title = [NSString stringWithFormat:@"%@", [categoryArray objectAtIndex:row]];

    // This portion pushes the categoryNavController.
    KeyCryptAppAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    [self.accountsTableViewController initWithTextSelected:selectedCategory];
    KeyCryptAppAppDelegate *appDelegate = (KeyCryptAppAppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.pickedCategory = selectedCategory;
    [delegate.categoryNavController pushViewController:accountsTableViewController animated:YES];

}

 }  



#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];

// Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}


- (void)dealloc {
[accountsTableViewController release];
[super dealloc];
}


@end

我用来删除行的代码(这是一个完全不同的tableview):

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

if (editingStyle == UITableViewCellEditingStyleDelete) {
    // Delete the row from the data source

    NSString *selectedCategory = [categoryArray objectAtIndex:indexPath.row];
    [categoryArray removeObjectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];


    [deleteCategoryTable reloadData];

    //NSString *selectedCategory = [categoryArray objectAtIndex:indexPath.row];

    sqlite3 *db= [KeyCryptAppAppDelegate getNewDBConnection];
    KeyCryptAppAppDelegate *appDelegate = (KeyCryptAppAppDelegate *)[[UIApplication sharedApplication] delegate];
    const char *sql = [[NSString stringWithFormat:@"Delete from Categories where Category = '%@';", selectedCategory]cString];
    const char *cmd = [[NSString stringWithFormat:@"pragma key = '%@' ", appDelegate.pragmaKey]cString];
    sqlite3_stmt *compiledStatement;
    sqlite3_exec(db, cmd, NULL, NULL, NULL);

    if (sqlite3_prepare_v2(db, sql, -1, &compiledStatement, NULL)==SQLITE_OK)
    {
        sqlite3_exec(db,sql,NULL,NULL,NULL);

    }
    else {
        NSAssert1(0,@"Error preparing statement", sqlite3_errmsg(db));
    }
    sqlite3_finalize(compiledStatement);
}



else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}   
}

3 个答案:

答案 0 :(得分:0)

在Tableview中的commitEditingStyle方法..你必须首先从类别数组中删除对象,&然后删除该行。 通过在最后一个中放置用于从数组中删除对象的代码来更改代码。

即。 将以下类型的代码放在最后 [categoryArray removeObjectAtIndex:indexPath.row]

答案 1 :(得分:0)

只是从数组中删除项目不会更新表格。你需要调用reloadData来更新tableview,甚至更好,调用tableview上的方法,让你插入或删除带动画的行而不重新加载整个表。

insertRowsAtIndexPaths:withRowAnimation:
deleteRowsAtIndexPaths:withRowAnimation:

答案 2 :(得分:0)

您需要在viewWillappear

中重新加载表格

添加此行

[yourTable reloadData];

因为表委托功能没有被调用重新出现在屏幕上。 但是当你再次进入下一个视图时,他们会调用这就是为什么在保存之后你不会在表格中获得更新信息但是你会得到更多导航,因为这次是在viewWillDisappear中调用reloadData。

为了解决删除问题,你需要按照iphoneDev ans和指令进行操作。