Skip to content

Instantly share code, notes, and snippets.

@keicoder
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

  • Save keicoder/8858465 to your computer and use it in GitHub Desktop.

Select an option

Save keicoder/8858465 to your computer and use it in GitHub Desktop.
objective-c : insert fake data in tableview (add a fake item to the list when you press the Add button)
//insert fake data in tableview (add a fake item to the list when you press the Add button)
//ChecklistItem.h
@interface ChecklistItem : NSObject
@property (nonatomic, copy) NSString *text;
@property (nonatomic, assign) BOOL checked;
- (void)toggleChecked;
@end
//ChecklistItem.m
@implementation ChecklistItem
@end
//ChecklistsViewController.h
@interface ChecklistsViewController : UITableViewController
- (IBAction)addItem;
@end
//ChecklistsViewController.m
@implementation ChecklistsViewController
{
NSMutableArray *_items;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_items = [[NSMutableArray alloc] initWithCapacity:20];
ChecklistItem *item;
item = [[ChecklistItem alloc] init];
item.text = @"Walk the dog";
item.checked = NO;
[_items addObject:item];
}
- (IBAction)addItem {
NSInteger newRowIndex = [_items count]; //현재 _items 배열의 수는 1이고 실제 배열이 있는곳은 index 0 이므로...
//뮤터블 배열에 추가
ChecklistItem *item = [[ChecklistItem alloc] init];
item.text = @"I am a new row";
item.checked = NO;
[_items addObject:item];
//table views use index-paths to identify rows
//so first make an NSIndexPath object that points to the new row, using newRowIndex variable
//index-path object now points to row 1 (in section 0)
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:newRowIndex inSection:0];
NSArray *indexPaths = @[indexPath];
[self.tableView insertRowsAtIndexPaths:indexPaths
withRowAnimation:UITableViewRowAnimationAutomatic];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_items count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChecklistItem"];
ChecklistItem *item = _items[indexPath.row];
//...
return cell;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment