Reputation: 134
I'm new to iOS and just trying to get data to display in UITableView
. I basically have a project set up about authors. I want to display author names etc. So i have an Author model and AuthorsViewController
which is a datasource and delegate for UITableView
etc. I'm using storyboard (MainStoryboard
) tableview and managed to connect it to AuthorsViewController
in the "Identity Inspector".
Image of Storyboard if it helps, thanks:
Here, first, is the model: Author.h
#import <Foundation/Foundation.h>
@interface Author : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *book;
@property (nonatomic) int year;
@end
Author.m
#import "Author.h"
@implementation Author
@end
Here is the AuthorsViewController.h
@interface AuthorViewController : UITableViewController
<UITableViewDataSource, UITableViewDelegate>
@end
And AuthorsViewController.m
#import "AuthorViewController.h"
@interface AuthorViewController ()
@property (nonatomic, strong) NSMutableArray *authors;
@end
@implementation AuthorViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_authors = [[NSMutableArray alloc] init];
Author *auth = [[Author alloc] init];
[auth setName:@"David Powers"];
[auth setBook:@"PHP Solutions"];
[auth setYear:2010];
[_authors addObject:auth];
auth = [[Author alloc] init];
[auth setName:@"Lisa Snyder"];
[auth setBook:@"PHP security"];
[auth setYear:2011];
[_authors addObject:auth];
auth = [[Author alloc] init];
[auth setName:@"Rachel Andrew"];
[auth setBook:@"CSS3 Tips, Tricks and Hacks"];
[auth setYear:2012];
[_authors addObject: auth];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_authors count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"AuthorCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell != nil)
{
cell = [[UITableViewCell alloc]
initWithStyle: UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Author *currentAuthor = [_authors objectAtIndex:[indexPath row]];
[[cell textLabel] setText: [currentAuthor name]];
NSLog(@"%@", [currentAuthor name]);
return cell;
}
@end
Upvotes: 0
Views: 3887
Reputation: 104092
Since you made the table view with its cell in the storyboard, you don't need the if (cell == nil) clause at all. You also need to call [self.tableView reloadData] as the last line in viewDidLoad.
Upvotes: 2