如何使用Button添加单元格?

时间:2011-03-17 15:27:55

标签: iphone objective-c uitableview nsmutablearray uibarbuttonitem

在这种情况下如何运作?我创建了一个NSMutabeArray * dataSource;在我的.h文件中,但收到了一堆错误:

“RootViewController.m:错误:语义问题:在'RootViewController *'类型的对象上找不到属性'dataSource'”

RootViewController.h

#import <UIKit/UIKit.h>

@interface RootViewController : UITableViewController {
NSMutableArray *dataSource;
}

@property (nonatomic,retain) NSMutableArray *dataSource;
- (IBAction)addButton:(id)sender;

@end

RootViewController.m

#import "RootViewController.h"

@implementation RootViewController
@synthesize dataSource;

- (void)viewDidLoad
{
[super viewDidLoad];
self.dataSource = [NSMutableArray arrayWithCapacity:1];
//adds right bar button.
UIBarButtonItem *addButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(add:)];
self.navigationItem.rightBarButtonItem=addButton;
[addButton release];

}

-(void)addButton:(id)sender{
[self.dataSource addObject:@"New Item"];
NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:[self.dataSource count] inSection:0];
[self.dataSource insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
}

2 个答案:

答案 0 :(得分:1)

有些记忆大师无疑会告诉你为什么@synthesize和可变数组和字典(和大概的集合)不能很好地结合在一起。我所知道的是,明确初始化你的可变数组,一切都会很好:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.dataSource = [NSMutableArray arrayWithCapacity:1];

    //adds right bar button.
    UIBarButtonItem *addButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(add:)];
    self.navigationItem.rightBarButtonItem=addButton;
    [addButton release];
}

当然,在dealloc中发布它。

答案 1 :(得分:0)

您尚未在.h文件中创建属性,并且您已使用自己的datasource变量。 请将self.dataSource替换为dataSource或为其创建属性。

@property (nonatomic,retain) NSMutableArray *dataSource;

并在.m文件中合成

@synthesize dataSource;