How to pass data from uitableview to detail view in storyboard - objective-c

I'm creating my first app in iOS 5 using storyboards. I have a tableviewcontroller embedded in a navigation controller and when you click on the cells in the tableviewcontroller some detail about that cell topic & a URL should be passed to a detail view. I use a PList to populate the tableview. I failed to pass the detail to detail view...
Here is my code (4 classes):
// NormalDataCell.m
#import "NormalDataCell.h"
#implementation NormalDataCell
#synthesize image = _image;
#synthesize nameLabel = _nameLabel;
#synthesize category = _category;
#synthesize webSiteURL = _webSiteURL;
#end
// normalData.m
#import "NormalData.h"
#implementation NormalData
#synthesize name = _name;
#synthesize image = _image;
#synthesize webSiteURL = _webSiteURL;
#synthesize category = _category;
- (id)initWithItem:(NSDictionary *)item {
self = [super init];
if (self) {
_name = [item objectForKey:#"name"];
_image = [UIImage imageNamed:[item objectForKey:#"image"]];
_webSiteURL = [item objectForKey:#"webSiteURL"];
_category = [item objectForKey:#"category"];
}
return self;
}
#end
#implementation NormalCategory
#synthesize category = _category;
#synthesize normalList = _normalList;
- (id)initWithArray:(NSMutableArray *)normalList {
self = [super init];
if (self) {
NSMutableArray *list = [[NSMutableArray alloc]init];
for (NSDictionary *item in normalList) {
NormalData *data = [[NormalData alloc]initWithItem:item];
[list addObject:data];
}
NormalData *data = [list objectAtIndex:0];
_category = data.category;
_normalList = list;
}
return self;
}
#end
// normalViewController.m
#import "NormalViewController.h"
#import "NormalData.h"
#import "NormalDataCell.h"
#import "NormalDetailView.h"
#interface NormalViewController ()
{
#private
NSMutableArray *_cellContentList;
}
#end
#implementation NormalViewController
#synthesize tableView; // Add this line of code
#synthesize roleArray;
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:#"http://vfttx.web.fc2.com/normal.plist"];
NSMutableArray *array = [NSMutableArray arrayWithContentsOfURL:url];
_cellContentList = [[NSMutableArray alloc]init];
for (NSMutableArray *item in array)
{
NormalCategory *category = [[NormalCategory alloc]initWithArray:item];
[_cellContentList addObject:category];
}
}
//How do I pass the name & webSiteURL to DetailView?
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"TableToWebSegue"]) {
NSIndexPath *path = [self.tableView indexPathForSelectedRow];
NSString *cellName = [[_cellContentList objectAtIndex:path.row] objectForKey:#"name"];
[segue.destinationViewController setDetailItem2:cellName];
NSString *urlPath = [[_cellContentList objectAtIndex:path.row] objectForKey:#"webSiteURL"];
[segue.destinationViewController setWebSiteURL:urlPath];
}
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [_cellContentList count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NormalCategory *category = [_cellContentList objectAtIndex:section];
return [category category];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NormalCategory *category = [_cellContentList objectAtIndex:section];
return [category.normalList count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"normalDataCell";
NormalDataCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
if (cell == nil) {
cell = [[NormalDataCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NormalCategory *category = [_cellContentList objectAtIndex:[indexPath section]];
NormalData *data = [category.normalList objectAtIndex:[indexPath row]];
[cell.nameLabel setText:data.name];
[cell.image setImage:data.image];
cell.webSiteURL = data.webSiteURL;
return cell;
}
#end
// NormalDetailView.m
#import "NormalDetailView.h"
#interface NormalDetailView ()
#end
#implementation NormalDetailView
#synthesize webSiteURL;
#synthesize webView;
#synthesize name = _name;
#synthesize detailItem2;
#synthesize testNameLabel;
- (void)viewDidLoad
{
[super viewDidLoad];
testNameLabel.text = detailItem2;
//If the URL is right, it will work.
NSString *strUrl = webSiteURL;
strUrl = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:strUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
}
#end

Presumably you're using segues to move between the different views.
Implement - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender on the view controller containing your table view and it will be called after the user taps the cell. It contains a reference to the segue object which you can use to find the sourceViewController and the destinationViewController, you can use these to set the data in the destination.

Related

NSArray - storing and retrieving data for a table using a button

I am trying to store data into NSArray using a button and then retrieve it to be displayed in a table. However, the table remains empty after the button has been pushed. I think the problem might have to do with how the Car object is being added to the array and then stored in NSData.
CarTableViewController.h
#import <UIKit/UIKit.h>
#import "CarDetailViewController.h"
#import "Car.h"
#interface CarListTableViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate>
#property Car *selectedCar;
#property NSMutableArray *listOfCars;
#property (strong, nonatomic) IBOutlet UITableView *carTableView;
#end
CarTableViewController.m
#import "CarListTableViewController.h"
#import "CarEntryViewController.h"
#implementation CarListTableViewController
#synthesize selectedCar, listOfCars, carTableView;
- (void)viewDidLoad {
[super viewDidLoad];
carTableView.delegate = self;
carTableView.dataSource = self;
}
- (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 listOfCars.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"carCell" forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"carCell"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.textLabel.numberOfLines = 0;
}
Car *tempCar =[listOfCars objectAtIndex:indexPath.row];
cell.textLabel.text =tempCar.make;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:true];
selectedCar = [listOfCars objectAtIndex:indexPath.row];
[self performSegueWithIdentifier:#"viewDetailsSegue" sender:nil];
}
#pragma mark - Navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
CarDetailViewController* vc = [segue destinationViewController];
vc.carObject = selectedCar;
}
- (NSArray*) retrieveDataFromNSUserDefaults {
NSMutableArray *objectArray = [NSMutableArray new];
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *dataRepresentingSavedArray = [currentDefaults objectForKey:#"savedArray"];
if (dataRepresentingSavedArray != nil) {
NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
if (oldSavedArray != nil)
objectArray = [[NSMutableArray alloc]
initWithArray:oldSavedArray];
else
objectArray = [[NSMutableArray alloc] init];
}
return objectArray;
}
- (void)storeDataInNSUserDefaults:(Car *)carToStore {
NSMutableArray *objectArray = [NSMutableArray arrayWithArray:[self retrieveDataFromNSUserDefaults]];
[objectArray addObject:carToStore];
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:objectArray] forKey:#"savedArray"];
}
#end
your code looks fine to me but I think you are not calling method to add data [self storeDataInNSUserDefaults:car] anywhere.

Displaying MapView in next VC from Table view cell by taking Latitude and longitude keys from json?

I am newbie to ios...please help me in solving this.i need to display map view in next view controller by tapping the row of a table view...
Here is my json:
[{"storeId":"STORE001","name":"Creamstone","latitude":"17.441934745594924","longitude":"78.45833734609187","storeAddress":"Begumpet, OPP: HPS","storeCity":"Hyderabad"},{"storeId":"STORE002","name":"Cream Stone","latitude":"17.37732708258546","longitude":"78.49484514445066","storeAddress":"near malakpet railway station\r\nchaderghat","storeCity":"Hyderabad"}]
here is my LocationTable.m
#import "LocationTable.h"
#import "LocationViewController.h"
#import "Stores.h"
#interface LocationTable ()
{
NSDictionary *coordinates;
}
#end
#define getStores #"http://192.168.28.9:8080/FoodCart/rest/storersrc/storebycity/hyderabad"
#implementation LocationTable
#synthesize json,locations;
- (void)viewDidLoad {
[super viewDidLoad];
self.title = #"Locations";
[self.tableView reloadData];
[self retrieveData];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"LocationCell"];
Stores *location = [locations objectAtIndex:indexPath.row];
cell.textLabel.text = location.name;
cell.detailTextLabel.text = location.storeAddress;
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
LocationViewController*lvc = [[LocationViewController alloc] init];
Stores *currentlocation = [locations objectAtIndex:indexPath.row];
lvc.latitude= currentlocation.latitude;
lvc.longitude=currentlocation.longitude;
[self.navigationController pushViewController:lvc animated:YES];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return locations.count;
}
-(void)retrieveData
{
NSError*error;
NSURL * url = [NSURL URLWithString:getStores];
NSData*data = [NSData dataWithContentsOfURL:url];
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
locations = [[NSMutableArray alloc] init];
for(int i=0;i<json.count;i++)
{
NSString * cStoreId = [[json objectAtIndex:i] objectForKey:#"storeId"];
NSString * cName = [[json objectAtIndex:i] objectForKey:#"name"];
NSNumber * cLatitude = [[json objectAtIndex:i] objectForKey:#"latitude"];
NSNumber * cLongitude = [[json objectAtIndex:i] objectForKey:#"longitude"];
NSString * cStoreAddress = [[json objectAtIndex:i] objectForKey:#"storeAddress"];
Stores *mylocations = [[Stores alloc] initWithstoreId:(NSString *) cStoreId andname:(NSString *) cName andlatitude:(NSNumber *) cLatitude andlongitude:(NSNumber *) cLongitude andstoreAddress:(NSString *) cStoreAddress];
[locations addObject:mylocations];
}
}
#end
Here is my LocationViewController.m:
#import "LocationViewController.h"
#import "MapView.h"
#import "LocationTable.h"
#interface LocationViewController ()
#property (nonatomic,strong) NSNumber *latitude;
#property (nonatomic,strong) NSNumber *longitude;
#property (nonatomic,strong) IBOutlet MKMapView *Mapview;
#end
#implementation LocationViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.Mapview.delegate = self;
MapView *mapPoint = [[MapView alloc] init];
mapPoint.coordinate = CLLocationCoordinate2DMake([self.Stores.latitude doubleValue], [self.Stores.longitude doubleValue]);
// Add it to the map view
[self.Mapview addAnnotation:mapPoint];
// Zoom to a region around the pin
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(mapPoint.coordinate, 500, 500);
[self.Mapview setRegion:region];
self.title = self.Stores.name;
}
Method Declaration Of MKAnnotationView
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
MKPinAnnotationView *view = nil;
static NSString *reuseIdentifier = #"MapView";
view = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIdentifier];
if(!view) {
view = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
view.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
view.canShowCallout = YES;
view.animatesDrop = YES;
}
return view;
}
#end
my jsonactivity is get data from url into table View , but now I want to display that data (latitude and longitude) on map view in the next View Controller, How Could I do this ? please help me, thanks in advance !
If the LocationViewController defined in a storyboard file, then you should create him via the next method:
[[UIStoryboard storyboardWithName:<your_storyboard_name> bundle:nil] instantiateViewControllerWithIdentifier:<your_controller_identifier>];
Otherwise, all IBOutlet-objects will be a nil.

Calling a method from another class doesn't return

I'm using parse.com. I'm trying to display comments but in order to get the comments I have to get the PFObject from my DetailViewController but it doesn't return the PFObject to CommentsViewController
EDIT
here is all the code. I'm new to objective c so I'm probably doing something stupid
CommentsView Controller
#import "CommentsViewController.h"
#import "DetailViewController.h"
#import "CommentsCell.h"
#interface CommentsViewController (){
NSArray *commentsArray;
id commentInstance;
}
#end
#implementation CommentsViewController
- (id)init {
if (self = [super init]) {
[self performSelector:#selector(commentsQuery)];
}
return self;
}
- (void)commentsQuery {
commentInstance = [[DetailViewController alloc] init];
PFObject *tempObj = [commentInstance placeObject];
PFQuery *query1 = [PFQuery queryWithClassName:#"activity"];
[query1 whereKey:#"type" equalTo:#"comment"];
[query1 whereKey:#"place" equalTo:[NSString stringWithFormat:#"%#", [tempObj objectId]]];
NSLog(#"%#", tempObj);
[query1 orderByDescending:#"createdAt"];
[query1 findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error){
commentsArray = [[NSArray alloc]initWithArray:objects];
NSLog(#"%lu", (unsigned long)[commentsArray count]);
}
}];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
static NSString *CellIdentifier = #"Cell";
CommentsCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[CommentsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
PFObject *placeObj = [commentInstance placeObject];
cell.username.text = #"test";
return cell;
}
#end
DetailsViewCOntroller
#import "DetailViewController.h"
#import "CommentsViewController.h"
#interface DetailViewController (){
CommentsViewController *test;
}
#end
#implementation DetailViewController
#synthesize place;
#synthesize userPhoto, message, username, checkCount, photo, scroller, commentsTableView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
test = [[CommentsViewController alloc] init];
self.commentsTableView.delegate = test;
self.commentsTableView.dataSource = test;
//Adjust the message label box height
CGSize textSize = [[place objectForKey:#"message"] sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:CGSizeMake(201, CGFLOAT_MAX) lineBreakMode: NSLineBreakByWordWrapping];
userPhoto.file = [place objectForKey:#"thumbnail"];
[userPhoto loadInBackground];
username.text = [place objectForKey:#"username"];
message.text = [place objectForKey:#"message"];
checkCount.text = [NSString stringWithFormat:#"%#", [place objectForKey:#"checkMarkCount"]];
[message sizeToFit];
if ([place objectForKey:#"photo"] != Nil){
photo.file = [place objectForKey:#"photo"];
[photo loadInBackground];
//[photo sizeToFit];
photo.frame = CGRectMake(6, textSize.height + 50, photo.frame.size.width, photo.frame.size.height);
float sizeOfContent = 0;
UIView *lLast = [scroller.subviews lastObject];
NSInteger wd = lLast.frame.origin.y;
NSInteger ht = lLast.frame.size.height;
NSLog(#"%#", lLast);
sizeOfContent = wd+ht;
scroller.contentSize = CGSizeMake(scroller.frame.size.width, sizeOfContent+100);
}
else{
float sizeOfContent = 0;
UIView *lLast = [scroller.subviews lastObject];
NSInteger wd = lLast.frame.origin.y;
NSInteger ht = lLast.frame.size.height;
NSLog(#"%#", lLast);
sizeOfContent = wd+ht;
scroller.contentSize = CGSizeMake(scroller.frame.size.width, sizeOfContent+100);
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)checkMarkButton:(UIButton *)sender {
}
- (PFObject *)placeObject{
return place;
}
#end
I do not see where you allocate place object. You call init and then try retrieving place. It should return nil. Here is your code:
commentInstance = [[DetailViewController alloc] init];
PFObject *tempObj = [commentInstance placeObject];
commentInstance is a new object. There is no init function defined in DetailViewController, hence commentInstance.place is nil and that is returned by placeObject method.
You define place as a property
#property ... place
That gives you a member variable _pace and two member functions, place() and setPlace(place). The object itself is not allocated for you.
Allocate place object in your init function, get rid of placeObject(), replace it with object.place call.
I got rid of all that and in my DetailViewController I added [test placeSet:place] in my viewDidLoad method. Then in CommentsViewController I did...
- (void)placeSet:(PFObject *)object{
place = object;
NSLog(#"place = %#", place);
}

UISearchBarDelegate on UITableView with Sections Issue

I'm having issues with implementing the UISearchBarDelegate on my UITableView with sections issue where every time I try to search for something inside the UITableView, either it doesn't display the desired result or it crashes the app with an error saying:
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
Here's inside my header file:
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UISearchDisplayDelegate, UISearchBarDelegate>
{
UITableView *mainTableView;
NSMutableArray *contentsList;
NSMutableArray *searchResults;
NSString *savedSearchTerm;
NSMutableArray *ivSectionKeys;
NSMutableDictionary *ivSectionContents;
}
#property (nonatomic, retain) IBOutlet UITableView *mainTableView;
#property (nonatomic, retain) NSMutableArray *contentsList;
#property (nonatomic, retain) NSMutableArray *searchResults;
#property (nonatomic, copy) NSString *savedSearchTerm;
#property (nonatomic, retain) NSMutableArray *sectionKeys;
#property (nonatomic, retain) NSMutableDictionary *sectionContents;
- (void)handleSearchForTerm:(NSString *)searchTerm;
#end
while this is inside my implementation file:
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize mainTableView;
#synthesize contentsList;
#synthesize searchResults;
#synthesize savedSearchTerm;
#synthesize sectionKeys = ivSectionKeys;
#synthesize sectionContents = ivSectionContents;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSMutableArray *keys = [[NSMutableArray alloc] init];
NSMutableDictionary *contents = [[NSMutableDictionary alloc] init];
NSString *colorKey = #"Colors";
NSString *clothingKey = #"Clothing";
NSString *miscKey = #"Misc";
[contents setObject:[NSArray arrayWithObjects:#"Red", #"Blue", nil] forKey:colorKey];
[contents setObject:[NSArray arrayWithObjects:#"Pants", #"Shirt", #"Socks", nil] forKey:clothingKey];
[contents setObject:[NSArray arrayWithObjects:#"Wankle Rotary Engine", nil] forKey:miscKey];
[keys addObject:clothingKey];
[keys addObject:miscKey];
[keys addObject:colorKey];
self.sectionKeys = keys;
self.sectionContents = contents;
// Restore search term
if (self.savedSearchTerm)
{
self.searchDisplayController.searchBar.text = self.savedSearchTerm;
}
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Save the state of the search UI so that it can be restored if the view is re-created.
self.savedSearchTerm = self.searchDisplayController.searchBar.text;
self.searchResults = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.mainTableView reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)handleSearchForTerm:(NSString *)searchTerm
{
self.savedSearchTerm = searchTerm;
if (self.searchResults == nil)
{
NSMutableArray *array = [[NSMutableArray alloc] init];
self.searchResults = array;
array = nil;
}
[self.searchResults removeAllObjects];
if ([self.savedSearchTerm length] != 0)
{
for (NSString *currentString in self.sectionContents)
{
if ([currentString rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location != NSNotFound)
{
[self.searchResults addObject:currentString];
}
}
}
}
#pragma mark -
#pragma mark UITableViewDataSource Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSInteger sections = [self.sectionKeys count];
return sections;
}
- (NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section
{
NSString *key = [self.sectionKeys objectAtIndex:section];
return key;
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
NSString *key = [self.sectionKeys objectAtIndex:section];
NSArray *contents = [self.sectionContents objectForKey:key];
NSInteger rows;
if (tableView == [[self searchDisplayController] searchResultsTableView])
rows = [self.searchResults count];
else
rows = [contents count];
NSLog(#"rows is: %d", rows);
return rows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *key = [self.sectionKeys objectAtIndex:indexPath.section];
NSArray *contents = [self.sectionContents objectForKey:key];
NSString *contentForThisRow = [contents objectAtIndex:indexPath.row];
if (tableView == [self.searchDisplayController searchResultsTableView])
contentForThisRow = [self.searchResults objectAtIndex:indexPath.row];
else
contentForThisRow = [contents objectAtIndex:indexPath.row];
static NSString *CellIdentifier = #"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = contentForThisRow;
return cell;
}
#pragma mark -
#pragma mark UITableViewDelegate Methods
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#pragma mark -
#pragma mark UISearchDisplayController Delegate Methods
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
[self handleSearchForTerm:searchString];
// Return YES to cause the search result table view to be reloaded.
return YES;
}
- (void)searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller
{
self.savedSearchTerm = nil;
[self.mainTableView reloadData];
}
#end
I think my issue is inside my for-loop but I'm not really sure.
You need to update all of your table view data source and delegate methods to handle both tables (you only do this in some):
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSInteger sections = [self.sectionKeys count];
return sections;
}
should be:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if (tableView == self.tableView) {
NSInteger sections = [self.sectionKeys count];
return sections;
} else { // assume it's the search table
// replace this with the actual result
return numberOfSectionsForSearchTable;
}
}

Simple twitter program not working

I'm using this tutorial to practice creating an extremely basic twitter app: http://www.codeproject.com/Articles/312325/Making-a-simple-Twitter-app-using-iOS-5-Xcode-4-2#setting-up-the-table-view
The only difference in my app is I'm only using tableView ViewController. I can't seem to get this to work.
ViewController.h
#interface ViewController : UIViewController {
NSArray *tweets;
}
-(void)fetchTweets;
#property (retain, nonatomic) IBOutlet UITableView *tableView;
#end
ViewController.m
#import "ViewController.h"
#import "Twitter/Twitter.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize tableView = _tableView;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self fetchTweets];
}
- (void)fetchTweets
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString: #"https://api.twitter.com/1/statuses/public_timeline.json"]];
NSError* error;
tweets = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
});
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return tweets.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"TweetCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *tweet = [tweets objectAtIndex:indexPath.row];
NSString *text = [tweet objectForKey:#"text"];
NSString *name = [[tweet objectForKey:#"user"] objectForKey:#"name"];
cell.textLabel.text = text;
cell.detailTextLabel.text = [NSString stringWithFormat:#"by %#", name];
return cell;
}
- (void)viewDidUnload
{
_tableView = nil;
[self setTableView:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
#end
you forgot to define delegate & datasource for your table, and didn't implement the protocols right as far as i see in your code,
try in your .h file:
#interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
{
// your implementation...
}
and in your .m file in viewDidLoad
self.tableView.dataSource = self;
self.tableView.delegate = self;
the numberOfRows, cellForRow, etc... methods wont work until you define your delegate & datasource for this table :)