Populate UITableView from NSMutableArray - ios

Having an issue where the array values do not display in my tableview cells, but can be printed out correctly with NSLog. Thanks in advance for your help!
TableViewCell .h
#import <UIKit/UIKit.h>
#interface TableViewCell : UITableViewCell
#property (strong, nonatomic) IBOutlet UIImageView *image;
#property (strong, nonatomic) IBOutlet UILabel *label;
#end
TableViewController.h
#import <UIKit/UIKit.h>
#interface TableViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate>
#property(nonatomic, strong) NSMutableArray *imagesArray;
#property(nonatomic, strong) NSMutableArray *namesArray;
#end
TableViewController.m
#import "TableViewController.h"
#import "TableViewCell.h"
#interface TableViewController ()
#end
#implementation TableViewController
#synthesize primaryWeaponNames = _primaryWeaponNames;
- (void)viewDidLoad {
[super viewDidLoad];
[self setupArrays];
}
- (void)setupArrays {
_namesArray = [[NSMutableArray alloc] initWithObjects:
#"NAME1", #"NAME2", #"NAME3"
nil];
self.imagesArray = [[NSMutableArray alloc] initWithObjects:
#"IMG1", #"IMG2", #"IMG3"
nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return _namesArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"TableViewCell";
TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
cell.nameLabel.text = [NSString stringWithFormat:#"%#", [_namesArray objectAtIndex:indexPath.row]];
NSLog(#"%#", _namesArray[indexPath.row]);
cell.image.image = [self.imagesArray objectAtIndex:indexPath.row];
[cell setAccessoryType: UITableViewCellAccessoryDisclosureIndicator];
return cell;
}

When you make the cell in a xib file, you should register the nib in viewDidLoad. Since you didn't do that, the dequeue method will return nil, and you're just creating a default cell (in the if (cell == nil) clause) instead of your custom cell. The default cell doesn't have a nameLabel or image property, so the lines to set the values of those outlets won't do anything.
[self.tableView registerNib:[UINib nibWithNibName:#"Your nib name here" bundle:nil] forCellReuseIdentifier:#"TableViewCell];

In your TableViewController class, you need to include
self.tableView.delegate = self;
self.tableView.datasource = self;
in your viewDidLoad method. Or you can do this in interface builder by right click dragging the table view in your tableview controller to file's owner and setting delegate, then repeat for datasource

Related

Can't set Custom UITableViewCell property - iOS

First of all I want to apologize for my bad english.
I'm having trouble to set the properties of my custom UITableViewCell (HistoricoCell).
When I try to set a property of my cell I get: Signal SIGABRT error:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// Dequeue the cell.
HistoricoCell *cell = (HistoricoCell *)[self.tblHistorico dequeueReusableCellWithIdentifier:#"CellIdentifier" forIndexPath:indexPath];
// Fetch Item
NSDictionary *item = [self.dbManager.arrColumnNames objectAtIndex:indexPath.row];
// Configure Table View Cell
[cell.lblCodigo setText:[NSString stringWithFormat:#"%#", item[#"codigo"]]];
[cell.btnFavoritar addTarget:self action:#selector(didTapButton:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
I followed a lot of tutorials and questions on the web but I stil with my error.
Can someone help me?
My code:
HistoricoCell.h
#import <UIKit/UIKit.h>
#interface HistoricoCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UILabel *lblCodigo;
#property (weak, nonatomic) IBOutlet UIButton *btnFavoritar;
#end
SecondViewController.h
#import <UIKit/UIKit.h>
#interface SecondViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
#property (weak, nonatomic) IBOutlet UITableView *tblHistorico;
SecondViewController.m
#import "SecondViewController.h"
#import "DBManager.h"
#import "HistoricoCell.h"
#interface SecondViewController ()
#property (nonatomic, strong) DBManager *dbManager;
#property (nonatomic, strong) NSArray *arrPeopleInfo;
-(void)loadData;
#end
#implementation SecondViewController
static NSString *CellIdentifier = #"CellIdentifier";
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// Make self the delegate and datasource of the table view.
self.tblHistorico.delegate = self;
self.tblHistorico.dataSource = self;
// Initialize the dbManager property.
self.dbManager = [[DBManager alloc] initWithDatabaseFilename:#"bernoullidb.sql"];
[self.tblHistorico registerClass:[HistoricoCell class] forCellReuseIdentifier:#"CellIdentifier"];
[self loadData];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)loadData{
// Form the query.
NSString *query = #"select * from tbHistorico";
// Get the results.
if (self.arrPeopleInfo != nil) {
self.arrPeopleInfo = nil;
}
self.arrPeopleInfo = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
// Reload the table view.
//[self.tblHistorico reloadData];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.arrPeopleInfo.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 60.0;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// Dequeue the cell.
HistoricoCell *cell = (HistoricoCell *)[self.tblHistorico dequeueReusableCellWithIdentifier:#"CellIdentifier" forIndexPath:indexPath];
// Fetch Item
NSDictionary *item = [self.dbManager.arrColumnNames objectAtIndex:indexPath.row];
// Configure Table View Cell
[cell.lblCodigo setText:[NSString stringWithFormat:#"%#", item[#"codigo"]]];
[cell.btnFavoritar addTarget:self action:#selector(didTapButton:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
- (void)didTapButton:(id)sender {
NSLog(#"%s", __PRETTY_FUNCTION__);
}
#end
You should set cell indentifier "CellIdentifier" for your cell in File Inspector
Or register your nib file if you add cell with nib:
UINib *itemNib = [UINib nibWithNibName:#"yourCell" bundle:nil];
[self.tableView registerNib:itemNib forCellReuseIdentifier:#"yourCellReuseIndentifier"];
I think your problem is in your cell creation: you try to dequeue a cell if it exists (i.e. recycle a previously used cell). that is OK, but, especially when the TableView is displayed for the first time, no previously used cell for this table exists. So, you have to create one if the dequeueReusableCellWithIdentifier call return nil.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// Dequeue the cell.
HistoricoCell *cell = (HistoricoCell *)[self.tblHistorico dequeueReusableCellWithIdentifier:#"HistoricoCellIdentifier" forIndexPath:indexPath];
if( cell == nil ) // no queuded cell to dequeue
{
// you have to create a fresh new one
cell = [HistoricoCell alloc] initWithStyle:<your cell style> reuseIdentifier:#"HistoricoCellIdentifier"];
}
// Fetch Item
NSDictionary *item = [self.dbManager.arrColumnNames objectAtIndex:indexPath.row];
// Configure Table View Cell
[cell.lblCodigo setText:[NSString stringWithFormat:#"%#", item[#"codigo"]]];
[cell.btnFavoritar addTarget:self action:#selector(didTapButton:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}

UITableViewCell Subtitle not showing up

I have my UITableView displaying JSON info being returned from a cloud code function. For some reason, it correctly displays the titles of the items being returned, but I can't get it to display the price as a subtitle of each cell. Setting the style as UITableViewCellStyleSubtitle doesn't seem to work, and gives me a warning stating Implicit conversion from enumeration type 'enum UITableviewCellStyle' to different enumeration type.
MatchCenterViewController.h:
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
#import "AsyncImageView.h"
#import "SearchViewController.h"
#interface MatchCenterViewController : UIViewController <UITableViewDataSource>
#property (nonatomic) IBOutlet NSString *itemSearch;
#property (nonatomic, strong) NSArray *imageURLs;
#property (strong, nonatomic) NSString *matchingCategoryCondition;
#property (strong, nonatomic) NSString *matchingCategoryLocation;
#property (strong, nonatomic) NSNumber *matchingCategoryMaxPrice;
#property (strong, nonatomic) NSNumber *matchingCategoryMinPrice;
#property (strong, nonatomic) NSArray *matchCenterArray;
#end
MatchCenterViewController.m:
#import "MatchCenterViewController.h"
#import <UIKit/UIKit.h>
#interface MatchCenterViewController () <UITableViewDataSource, UITableViewDelegate>
#property (nonatomic, strong) UITableView *matchCenter;
#end
#implementation MatchCenterViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// self.matchCenter = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
// _matchCenter.dataSource = self;
// _matchCenter.delegate = self;
// [self.view addSubview:self.matchCenter];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.matchCenter = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewCellStyleSubtitle];
self.matchCenter.frame = CGRectMake(0,50,320,self.view.frame.size.height-200);
_matchCenter.dataSource = self;
_matchCenter.delegate = self;
[self.view addSubview:self.matchCenter];
self.matchCenterArray = [[NSArray alloc] init];
}
- (void)viewDidAppear:(BOOL)animated
{
self.matchCenterArray = [[NSArray alloc] init];
[PFCloud callFunctionInBackground:#"MatchCenterTest"
withParameters:#{
#"test": #"Hi",
}
block:^(NSDictionary *result, NSError *error) {
if (!error) {
self.matchCenterArray = [result objectForKey:#"Top 3"];
dispatch_async(dispatch_get_main_queue(), ^{
[_matchCenter reloadData];
});
NSLog(#"Test Result: '%#'", result);
}
}];
[self.matchCenter registerClass:[UITableViewCell class] forCellReuseIdentifier:#"Cell"];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.matchCenterArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSDictionary *matchCenterDictionary= [self.matchCenterArray objectAtIndex:indexPath.row];
cell.textLabel.text = [matchCenterDictionary objectForKey:#"Title"];// title of the item
cell.detailTextLabel.text = [matchCenterDictionary objectForKey:#"Price"];// price of the item
return cell;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
#end
The cell you have registered is a default styled UITableViewCell, it does not have a subTitle. You can't change the style of the cell once it's created.
You basically have two options:
create a simple UITableViewCell subclass that uses UITableViewCellStyleSubtitle (or any other style of your choice)
#interface MyTableViewCell : UITableViewCell
#end
#implementation MyTableViewCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
// overwrite style
self = [super initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];
return self;
}
#end
...
[self.matchCenter registerClass:[MyTableViewCell class] forCellReuseIdentifier:#"Cell"];
Or return to the old style dequeue technique where you create a cell if none could be dequeued
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
// if no cell could be dequeued create a new one
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
/* configure */
}
If you do this, you have to remove the registerClass:forCellReuseIdentifier: call.
I would go with option one, because most likely pretty soon you will figure out that the built in cells are very limited and you want to add your own views (e.g. labels, image views). And if you use a subclass you can use properties to access those views, and don't have to use hacks like tags to access them.
In Table View subtitle is not present otherwise you customize your cell
use detail text label
cell.detailTextLabel.text = [array objectForKey:#"Value"];

View flashes when popToRootViewController

I am having a problem with popToRootViewController. I have a root view A and a table view B. And when a row is selected in the table view I pass a string back to the root view and depending on the string. I change the title of buttons on A.
I have made a very simple version of this and put it on gitHub at this link: https://github.com/spennyf/didSelect_test. I am doing this because it is very hard to explain until you actually run this on your phone of the simulator. And see the flash. I don't know why it is happening or how to fix it. Any help would be greatly appreciated I will also post most of the code below, but if you could see the flash for yourself I think it would help explain the problem. Heres the code:
viewControllerA.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#property (strong, nonatomic) IBOutlet UIButton *btn1;
#property (strong, nonatomic) IBOutlet UIButton *btn2;
#property (strong, nonatomic) IBOutlet NSString *object;
#end
viewControllerA.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)viewWillAppear:(BOOL)animated {
NSLog(#"object: %#", _object);
if ([_object isEqualToString:#"object1"]) {
[_btn1 setTitle:#"new1" forState:UIControlStateNormal];
}
if ([_object isEqualToString:#"object2"]) {
[_btn2 setTitle:#"new2" forState:UIControlStateNormal];
}
}
#end
tableviewB.m
#import "TableViewController.h"
#import "ViewController.h"
#interface TableViewController () {
NSMutableArray *_objects;
}
#end
#implementation TableViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_objects = [[NSMutableArray alloc] init];
NSDictionary *obj1 = [[NSDictionary alloc] initWithObjectsAndKeys:#"object1", #"title", nil];
NSDictionary *obj2 = [[NSDictionary alloc] initWithObjectsAndKeys:#"object2", #"title", nil];
// NSDictionary *obj3 = [[NSDictionary alloc] initWithObjectsAndKeys:#"rpi", #"title", nil];
[_objects addObject:obj1];
[_objects addObject:obj2];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return _objects.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
//NSLog(#"%#", _objects);
cell.textLabel.text = [[_objects objectAtIndex:indexPath.row] objectForKey:#"title"];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
ViewController *myController = (ViewController *)[self.navigationController.viewControllers objectAtIndex:0];
myController.object = [[_objects objectAtIndex:indexPath.row] objectForKey:#"title"];
[self.navigationController popToRootViewControllerAnimated:YES];
}
#end
Again thanks for the help.
There is no problem with your code. It is intended behavior for UIButtons of type UIButtonTypeSystem to flash when its title is changed.
A simple workaround is to set the type of your buttons to UIButtonTypeCustom.
Edit:
You can change the type of the button in Interface Builder:

Why are my mutable arrays and table views behaving unexpectedly?

I'm building a sign-in app. It has two table views. One lists people who have visited before (existingNames), and one lists the current people signed in (names).
At certain points in my code the only mutable array that does not crash the program when accessed is names.
names and existingNames seems to somehow be reversed as well. When I try to remove from names, the program crashes. When I remove from existingNames, the changes are reflected in tableView2, but tableView2 is supposed to be associated with names.
In the app's current state everything is "working" except for accessing any company arrays. I put quotes around working because of the names and existingNames being used backwards.
Any insight into what might be causing the problem would be much appreciated!
.h:
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>{
UITableView *tableView;
}
#property (weak, nonatomic) IBOutlet UITextField *nameField;
#property (weak, nonatomic) IBOutlet UITextField *companyField;
#property (nonatomic, retain) NSMutableArray *names;
#property (nonatomic, retain) NSMutableArray *companies;
#property (nonatomic, retain) NSMutableArray *existingNames;
#property (nonatomic, retain) NSMutableArray *existingCompanies;
- (IBAction)add:(id)sender;
- (IBAction)addExisting:(id)sender;
- (IBAction)remove:(id)sender;
- (IBAction)submit:(id)sender;
#property (strong, nonatomic) IBOutlet UITableView *tableView1;
#property (weak, nonatomic) IBOutlet UITableView *tableView2;
#end
.m:
#import "ViewController.h"
#import <MessageUI/MessageUI.h>
#interface ViewController () <MFMailComposeViewControllerDelegate>
#end
#implementation ViewController
#synthesize nameField;
#synthesize companyField;
#synthesize names;
#synthesize companies;
#synthesize existingNames;
#synthesize existingCompanies;
#synthesize tableView1 = _tableView1;
#synthesize tableView2 = _tableView2;
int rowNumber1;
int rowNumber2;
- (void)viewDidLoad
{
[super viewDidLoad];
self.names = [[NSMutableArray alloc] init];
self.companies = [[NSMutableArray alloc] init];
self.existingNames = [[NSMutableArray alloc] init];
self.existingCompanies = [[NSMutableArray alloc] init];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.tableView1){
return [existingNames count];
}
else if (tableView == self.tableView2){
return [names count];
}
return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableItem";
UITableViewCell *cell;
if (tableView == self.tableView1){
cell = [_tableView1 dequeueReusableCellWithIdentifier:simpleTableIdentifier];
}
else if (tableView == self.tableView2){
cell = [_tableView2 dequeueReusableCellWithIdentifier:simpleTableIdentifier];
}
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
if (tableView == self.tableView1){
cell.textLabel.text = [existingNames objectAtIndex:indexPath.row];
}
else if (tableView == self.tableView2){
cell.textLabel.text = [names objectAtIndex:indexPath.row];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if (tableView == self.tableView1){
rowNumber1 = indexPath.row;
}
else if (tableView == self.tableView2){
rowNumber2 = indexPath.row;
}
}
- (IBAction)add:(id)sender {
BOOL exists = [existingNames containsObject:nameField.text];
if(exists == FALSE){
[names addObject:nameField.text];
[companies addObject:companyField.text];
[existingNames addObject:nameField.text];
[existingCompanies addObject:companyField.text];
}
else{
[names addObject:nameField.text];
[companies addObject:companyField.text];
}
[_tableView1 reloadData];
[_tableView2 reloadData];
nameField.text=#"";
companyField.text=#"";
}
- (IBAction)addExisting:(id)sender {
[existingNames addObject:[names objectAtIndex:rowNumber1]];
//[companies addObject:[existingCompanies objectAtIndex:rowNumber]];
[_tableView2 reloadData];
}
- (IBAction)remove:(id)sender {
[existingNames removeObjectAtIndex:rowNumber2];
[existingCompanies removeObjectAtIndex:rowNumber2];
[_tableView2 reloadData];
}
#end
The following methods are part of the UITableViewDataSource and UITableViewDelegate protocols
tableView:numberOfRowsInSection:
tableView:cellForRowAtIndexPath:
tableView:didSelectRowAtIndexPath:
and will be called by your table view assuming you've property assigned the table view's delegate and dataSource properties. These methods, however,
tableView2:numberOfRowsInSection:
tableView2:cellForRowAtIndexPath:
tableView2:didSelectRowAtIndexPath:
are not part of the protocol and won't ever get called by the table view. It looks like you may be confusing your property names, e.g. tableView, with with the protocol method names, e.g. tableView:numberOfRowsInSection:. What you need to do is:
If you haven't already done so, set your view controller as the delegate and dataSource for both your tableView and tableView2.
In each of the data source and delegate methods that you need to implement, handle the cases for both tables.
For example, your tableView:numberOfRowsInSection: method would look like:
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.tableView) {
return [existingNames count];
}
else if (tableView == self.tableView2) {
return [names count];
}
return 0;
}

iOS reload UITableView using UISegmentedControl

Hi I'm trying to reload my table view based off of two different arrays. Which array should be loaded is determined by a segment control in the navigation bar. Currently it only will load the first array and nothing happens when the segment control is pressed. Below is my code any help as to why this isn't working is greatly appreciated. I've also checked that my IBAction segmenter is connected in the nib.
MessageViewController.h
#import <UIKit/UIKit.h>
#interface MessageViewController : UIViewController<UITableViewDelegate> {
IBOutlet UISegmentedControl *segmentControl;
IBOutlet UINavigationBar *navBar;
IBOutlet UITableView *tableView;
}
#property (retain, nonatomic) IBOutlet UISegmentedControl *segmentControl;
#property (retain, nonatomic) IBOutlet UITableView *tableView;
#property (nonatomic, retain) NSMutableArray *inbox;
#property (nonatomic, retain) NSMutableArray *sent;
#end
MessageViewController.m
#import "MessageViewController.h"
#interface MessageViewController () <UITableViewDelegate>
#end
#implementation MessageViewController
#synthesize segmentControl;
#synthesize inbox;
#synthesize sent;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.tabBarItem.title = NSLocalizedString(#"Messages", #"Messages");
self.tabBarItem.image = [UIImage imageNamed:#"mail_2_icon&32"];
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.delegate = self;
self.inbox = [NSMutableArray arrayWithObjects:#"testing", #"test", #"another", nil];
self.sent = [NSMutableArray arrayWithObjects:#"test", #"another", #"testing", nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#pragma mark Table view methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if(segmentControl.selectedSegmentIndex == 0){
return [inbox count];
}else if(segmentControl.selectedSegmentIndex == 1){
return [sent count];
}else{
return [inbox count];
}
}
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
if(segmentControl.selectedSegmentIndex == 0){
NSString *cellValue = [inbox objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
}else if(segmentControl.selectedSegmentIndex == 1){
NSString *cellValue = [sent objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
}else{
NSString *cellValue = [inbox objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
}
return cell;
}
-(IBAction)segmenter{
[tableView reloadData];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}
- (void)dealloc {
[inbox release];
[sent release];
[segmentControl release];
[segmentControl release];
[super dealloc];
}
- (void)viewDidUnload {
[self setSegmentControl:nil];
[segmentControl release];
segmentControl = nil;
[super viewDidUnload];
}
#end
Not sure why it wasn't working in the end all I did was delete the three classes and redo everything with the code above something must have just got borked along the way but it's working now and I'm a happy camper. Didn't need the delegate stuff either since that's all done in the nib so my original code worked fine.
set the delegate and datasource methods and take breakpoint to check the data . your code is right .
tableview.delegate=self;
tableView.datasource=self;
The only problem I see is that you're using a view controller with a table view in it, but you're not setting up the delegate for it in your viewDidLoad, and you're not implementing the delegate for your view controller.
#interface MessageViewController () <UITableViewDelegate, UITableViewDataSource>
#end
In viewDidLoad:
self.tableView.delegate = self;
self.tableView.dataSource = self;
Also make sure you have everything hooked up properly in IB, both your segmented control and your table view.
EDIT: I made my own test as per what you're trying to do, Here's my own implementation file

Resources