How to add a cell with Button?
How would this work in this case? I created a NSMutabeArray *dataSource; in my .h file, but getting a bunch of errors:
"RootViewController.m: error: Semantic Issue: Property 'dataSource' not found on object of type 'RootViewController *'"
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.dataSou开发者_如何学Crce addObject:@"New Item"];
NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:[self.dataSource count] inSection:0];
[self.dataSource insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
}
Some memory-guru will no doubt be able to tell you why @synthesize and mutable arrays and dictionaries (and sets, presumably) do not play well together. All I know is, initialize your mutable array explicitly and all will be well:
- (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];
}
And, of course, release it in the dealloc.
You have not created property in .h file and you have used datasource variable with self. please replace self.dataSource with dataSource or create property for it.
@property (nonatomic,retain) NSMutableArray *dataSource;
and synthesize in .m file
@synthesize dataSource;
精彩评论