Last active
August 29, 2015 13:56
-
-
Save datinc/9075686 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// this is an answer for SO question http://stackoverflow.com/q/21859288/1449607 | |
@interface TableViewController : UITableViewController | |
@end | |
@interface TableViewController () | |
@property (nonatomic, strong) NSMutableArray* books; | |
@property (nonatomic, strong) NSString* path; | |
@end | |
@implementation TableViewController | |
- (void)viewDidLoad | |
{ | |
[super viewDidLoad]; | |
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; | |
self.path = [documentsDirectory stringByAppendingPathComponent:@"books.plist"]; | |
// Attempt to load saved data from the documents directory | |
if ([[NSFileManager defaultManager] fileExistsAtPath:self.path]){ | |
self.books = [NSMutableArray arrayWithContentsOfFile:self.path]; | |
}else{ | |
// No saved data in documents directory so we need to load the data from the bundle | |
NSString* bundlePath = [[NSBundle mainBundle] pathForResource:@"books" ofType:@"plist"]; | |
self.books = [NSMutableArray arrayWithContentsOfFile:bundlePath]; | |
} | |
} | |
#pragma mark - Table view data source | |
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section | |
{ | |
// Return the number of rows in the section. | |
return self.books.count; | |
} | |
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath | |
{ | |
static NSString *CellIdentifier = @"Cell"; | |
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; | |
if (cell == nil){ | |
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier]; | |
} | |
NSDictionary* book = self.books[indexPath.row]; | |
cell.accessoryType = [book[@"checkbox"] boolValue] ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone; | |
cell.textLabel.text = book[@"title"]; | |
cell.detailTextLabel.text = book[@"price"]; | |
cell.imageView.image = [UIImage imageWithContentsOfFile:book[@"thumbnail"]]; | |
return cell; | |
} | |
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ | |
NSMutableDictionary* book = self.books[indexPath.row]; | |
book[@"checkbox"] = [NSNumber numberWithBool:[book[@"checkbox"] boolValue]]; | |
[self.books writeToFile:self.path atomically:YES]; | |
[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment