C/xcode geeks!
I have been struggling with this error for hours now, and I don't seem to find the solution, although it seems as many people have had the exact same problem.
See code:
//
// ListViewController.m
// Puns
//
// Created by Amit Bijlani on 12/13/11.
// Copyright (c) 2011 Treehouse Island Inc. All rights reserved.
//
#import "ListViewController.h"
#import "BlogPost.h"
//#import "Pun.h"
#import "PunsTableViewCell.h"
#import "DetailViewController.h"
#implementation ListViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
#pragma mark - Segue
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
NSLog(#"0");
if ( [[segue identifier] isEqualToString:#"ShowMenu"] ){
NSLog(#"1");
DetailViewController *dvc = (DetailViewController *)[segue destinationViewController];
dvc.menu = [self.blogPosts objectAtIndex:[[self.tableView indexPathForSelectedRow] row]];
}
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// GET WEB DATA SOURCE (JSON)
// The url
NSURL *blogURL = [NSURL URLWithString:#"http://constantsolutions.dk/json.html"];
// The data
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
// Error variable
NSError *error = nil;
// jsonData to serialization
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
// Get array 'posts'
self.blogPosts = [NSMutableArray array];
NSArray *blogPostsArray = [dataDictionary objectForKey:#"posts"];
for (NSDictionary *bpDictionary in blogPostsArray) {
// Get title
// Will only retrieve data, if TITLE exists
BlogPost *blogPost = [BlogPost blogPostWithTitle:[bpDictionary objectForKey:#"title"]];
// Get the content
blogPost.content = [bpDictionary objectForKey:#"content"];
// Get thumbnail
blogPost.thumbnail = [bpDictionary objectForKey:#"thumbnail"];
// Get date
blogPost.date = [bpDictionary objectForKey:#"date"];
// Get price
blogPost.price = [bpDictionary objectForKey:#"price"];
// Add the object to blogPosts array
[self.blogPosts addObject:blogPost];
}
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#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 [self.blogPosts count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"PunTableViewCell";
PunsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[PunsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
BlogPost *blogPost = [self.blogPosts objectAtIndex:indexPath.row];
cell.menuTitle.text = blogPost.title;
cell.menuContent.text = blogPost.content;
if([blogPost.price length] == 0) {
[cell.menuPrice setHidden:YES];
} else {
cell.menuPrice.text = blogPost.price;
}
return cell;
}
#end
As you can see, I have implented NSLog() inside the prepareForSegue, but it is not triggered.
Do you guys have any idea what I am doing wrong? I am pretty new to this, so I still haven't found out this whole iPhone development thing. So bare over with me if the solution is simple :o).
Thanks in advance!
You have a name for the segue, so does that mean you created it by dragging from a button or table view cell to the other view controller and then selected it and named it in xcode? if you are programmatically changing the view it wont be called but you can manually call a method before swapping views to prepare
I had a similar issue in going about sharing information in ios between views where the answer may be helpful.
In particular from the answer on that post where he says:
"in your .m file you would trigger you segue - maybe on a button or some action. sounds like you already have this:"
[self performSegueWithIdentifier:#"viewB" sender:self];
--
Swapping your segue name in of course.
Related
Hi when I do for loop to get all documents from a collection. I add the car object to the NSMutablearray and when I debug i can see that the objects are being added to the array but when i want it to display in the table and get the count of the array I call the [self.mycars count] to get the count but the count is nil and i cant get information from the cell.textLabel.text = vehicle.name; so what am i doing wrong.
#import "TableViewController.h"
#import "Car.h"
#import "Vehicle.h"
#interface TableViewController ()
#end
#implementation TableViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
self.db = [FIRFirestore firestore];
self.myCars = [[NSMutableArray alloc] init];
[[[[self.db collectionWithPath:#"users"] documentWithPath:[FIRAuth auth].currentUser.uid]
collectionWithPath:#"cars"] getDocumentsWithCompletion:^(FIRQuerySnapshot *snapshot, NSError *error) {
if (error != nil) {
NSLog(#"Error getting documents: %#", error);
} else {
for (FIRDocumentSnapshot *document in snapshot.documents) {
NSLog(#"%# => %#", document.documentID, document.data);
Car *car = [[Car alloc] initWithCarName:[document valueForField:#"carname"] andCarStyle:[document valueForField:#"carstyle"]
andCarColour:[document valueForField:#"colour"] andCarYear:[document valueForField:#"caryear"]
andCarDoors:[document valueForField:#"doors"] andCarSeat:[document valueForField:#"seat"] andCarWheels:[document valueForField:#"wheels"]
andCarTankCapacity:[document valueForField:#"tankcapacity"] andCarHorsePower:[document valueForField:#"horsepower"] andCarModelName:[document valueForField:#"modelname"]];
NSLog(#"Car name:%#", car.name);
[self.myCars addObject:car];
}
}
}];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.myCars count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cellidentifier" forIndexPath:indexPath];
// Configure the cell...'
Vehicle *vehicle = [self.myCars objectAtIndex:indexPath.row];
cell.textLabel.text = vehicle.name;
return cell;
}
#end
You need to reload data manually after changing/updating your datasource (self.myCars in this case) which mean you need to add [self.tableView reloadData]; after for loop. If it still is not working, you might want to check if self.myCars is initialized yet.
I have a problem with my tableview. I'm trying to make a program that downloads job details from my database and lists them. The tableview is still blank, the view is connected to the specific controller and I have checked that the JSON feed and cell identifier are OK. My cell rows are also strange, the row lines continue over the right edge though I have aligned the tableview object correctly. I had similar problems with my previous project but didn't know what was wrong.
Here is a part of the code (Source from: http://codewithchris.com/iphone-app-connect-to-mysql-database/)
JobViewer.m
#interface JobViewer()
{
NSMutableData *_downloadedData;
}
#end
#implementation JobViewer
- (void)downloadItems
{
// Getting json file
NSURL *jsonFileURL = [NSURL URLWithString:#"here is my correct URL"];
//Making request
NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:jsonFileURL];
//Creating NSURLConnection with the request
[NSURLConnection connectionWithRequest:urlRequest delegate:self];
}
#pragma mark NSURLConnectionDataProtocol Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//Initialize data
_downloadedData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//Append the data that was downloaded
[_downloadedData appendData:data];
}
- (void)connectionDidFinishDownloading:(NSURLConnection *)connection
{
//Creating array for the information
NSMutableArray *_jobs = [[NSMutableArray alloc] init];
// Parsing the JSON file
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:_downloadedData options:NSJSONReadingAllowFragments error:&error];
//Looping through JSON objects and storing them into array
for (int i = 0; i < jsonArray.count; i++)
{
NSDictionary *jsonObject = jsonArray[i];
//Creating a new object and getting data from JSON element
Job *newJob = [[Job alloc] init];
newJob.jobid = jsonObject[#"Job_id"];
newJob.companyid = jsonObject[#"Company_id"];
newJob.customer = jsonObject[#"Customer"];
newJob.phone = jsonObject[#"Phone"];
newJob.email = jsonObject[#"Email"];
newJob.address = jsonObject[#"Address"];
newJob.city = jsonObject[#"City"];
newJob.header = jsonObject[#"Header"];
newJob.notes = jsonObject[#"Notes"];
newJob.date = jsonObject[#"Date"];
newJob.driver = jsonObject[#"Driver"];
//Added question to array
[_jobs addObject:newJob];
}
// Passing the done data and passing items back
if (self.delegate)
{
[self.delegate itemsDownloaded:_jobs];
}
}
#end
MainViewController.m
#interface MainViewController ()
{
JobViewer *_jobViewer;
NSArray *_listObjects;
}
#end
#implementation MainViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.mainList.delegate = self;
self.mainList.dataSource = self;
_listObjects = [[NSArray alloc] init];
_jobViewer = [[JobViewer alloc] init];
_jobViewer.delegate = self;
[_jobViewer downloadItems];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)itemsDownloaded:(NSArray *)items
{
_listObjects = items;
[self.mainList reloadData];
}
#pragma mark Table View Delegate Methods
// You may remove this method
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _listObjects.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifier = #"InfoCell";
UITableViewCell *newCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
Job *item = _listObjects[indexPath.row];
newCell.textLabel.text = item.address;
//[newCell setBackgroundColor:[UIColor blackColor]];
return newCell;
}
/*
#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
You likely need to add "InfoCell" as the reuse identifier in your Storyboard.
Probably your tableView doesn't recognise the cell so you should add the cell at tableView in the storyboard and it is called "InfoCell"
If you don't want to add cell into tableView in the storyboard and you have a xib with your cell. you can call in your viewController this method:
[tableView registerNib:[UINib nibWithNibName:#"IndoCell" bundle:nil] forCellReuseIdentifier:#"IndoCell"];
that if your nib is called "IndoCell.xib"
I have a pull to refresh setup. It's currently calling [self.tableView reloadData]; but It's not reloading my parsed Json data from the blogData method. Is theres something I'm missing?
My controller is like this:
//
// ARTableViewController.m
// WorldCupLive
//
// Created by Adam Rais on 14/06/2014.
// Copyright (c) 2014 Adam Rais. All rights reserved.
//
#import "ARTableViewController.h"
#import "ARModal.h"
#interface ARTableViewController ()
#end
#implementation ARTableViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.blogPost = [[ARModal alloc] init];
self.blogPost.jsonMutable = [NSMutableArray array];
for (NSDictionary *post in self.blogPost.blogData) {
ARModal *bp = [ARModal blogPostWithHome:[[post objectForKey:#"home"] objectForKey:#"text"]];
bp.away = [[post objectForKey:#"away"] objectForKey:#"text"];
bp.result = [[post objectForKey:#"result"] objectForKey:#"text"];
bp.info = [post objectForKey:#"info"];
bp.homeImage = [[post objectForKey:#"homeimage"] objectForKey:#"src"];
[self.blogPost.jsonMutable addObject:bp];
}
[self randomBackgroundImage];
self.tableView.contentInset = UIEdgeInsetsMake(0.0f, -10.0f, 0.0f, 0.0f);
// Initialize Refresh Control
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
// Configure Refresh Control
[refreshControl addTarget:self action:#selector(refresh:) forControlEvents:UIControlEventValueChanged];
// Configure View Controller
[self setRefreshControl:refreshControl];
}
-(void)randomBackgroundImage {
UIImage *image = self.blogPost.imageUI;
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
self.tableView.backgroundView = imageView;
self.tableView.backgroundView.layer.zPosition -= 1;
}
- (void)refresh:(id)sender
{
NSLog(#"Refreshing");
[self.tableView reloadData];
[self randomBackgroundImage];
// End Refreshing
[(UIRefreshControl *)sender endRefreshing];
}
- (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 [self.blogPost.jsonMutable count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
// Configure the cell...
ARModal *post = [self.blogPost.jsonMutable objectAtIndex:indexPath.row];
NSData *imageData = [NSData dataWithContentsOfURL:post.jsonURL];
UIImage *image = [UIImage imageWithData:imageData];
cell.textLabel.text = [[[[[post.home stringByAppendingString:#" "]stringByAppendingString:#" "] stringByAppendingString:post.bst] stringByAppendingString:#" "] stringByAppendingString:post.away];
cell.detailTextLabel.text = post.info;
cell.imageView.image = image;
cell.backgroundColor = [UIColor colorWithWhite:1.000 alpha:0.000];
return cell;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
/*
#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
And my modal:
//
// ARModal.m
// WorldCupLive
//
// Created by Adam Rais on 14/06/2014.
// Copyright (c) 2014 Adam Rais. All rights reserved.
//
#import "ARModal.h"
#implementation ARModal
-(id)initWithHome:(NSString *)home {
self = [super init];
if (self) {
_home = home;
_away = nil;
_result = nil;
_info = nil;
_homeImage = nil;
}
return self;
}
+(id)blogPostWithHome:(NSString *)home {
return [[self alloc] initWithHome:home];
}
-(NSArray *)blogData {
NSURL *jsonURL = [NSURL URLWithString:#"http://www.kimonolabs.com/api/2nfgfo2s?apikey=1a1f5f323969d5157af8a8be857026c2"];
NSData *jsonData = [NSData dataWithContentsOfURL:jsonURL];
NSError *jsonError = nil;
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&jsonError];
NSArray *jsonArray = [[jsonDictionary objectForKey:#"results"] objectForKey:#"collection1"];
if (blogData == nil) {
blogData = jsonArray;
}
return blogData;
}
-(NSURL *)jsonURL {
return [NSURL URLWithString:self.homeImage];
}
-(NSString *)bst {
NSString *sentence = self.result;
NSString *word = #"-";
NSString *wordTwo = #"00.00";
NSString *wordThree = #"01.00";
NSMutableArray *bstArray = [NSMutableArray array];
if ([sentence rangeOfString:word].location != NSNotFound) {
NSLog(#"Found the string");
[bstArray addObject:sentence];
} else if ([sentence rangeOfString:wordTwo].location != NSNotFound) {
NSLog(#"time is 23:00");
[bstArray addObject:#"23:00"];
} else if ([sentence rangeOfString:wordThree].location != NSNotFound) {
NSLog(#"time is 00:00");
[bstArray addObject:#"00:00"];
} else {
float floatOne = [sentence floatValue];
float floatFinal = floatOne - 1.000000;
NSString *str = [NSString stringWithFormat:#"%f", floatFinal];
NSString *bstFinal = [str substringToIndex:[str length] - 4];
[bstArray addObject:bstFinal];
}
return [bstArray objectAtIndex:0];
}
-(UIImage *)imageUI {
NSArray *imageArray = #[[UIImage imageNamed:#"Algeria"],[UIImage imageNamed:#"Argentina"],[UIImage imageNamed:#"Australia"],[UIImage imageNamed:#"Belgium"],[UIImage imageNamed:#"Bosnia-Herzegovina"],[UIImage imageNamed:#"Switzerland"],[UIImage imageNamed:#"Uruguay"],[UIImage imageNamed:#"USA"],[UIImage imageNamed:#"Brazil"],[UIImage imageNamed:#"Cameroon"],[UIImage imageNamed:#"Chile"],[UIImage imageNamed:#"Colombia"],[UIImage imageNamed:#"Costa Rica"],[UIImage imageNamed:#"Côte d'Ivoire"],[UIImage imageNamed:#"Croatia"],[UIImage imageNamed:#"Ecuador"],[UIImage imageNamed:#"England"],[UIImage imageNamed:#"France"],[UIImage imageNamed:#"Germany"],[UIImage imageNamed:#"Ghana"],[UIImage imageNamed:#"Greece"],[UIImage imageNamed:#"Honduras"],[UIImage imageNamed:#"Iran"],[UIImage imageNamed:#"Italy"],[UIImage imageNamed:#"Japan"],[UIImage imageNamed:#"Mexico"],[UIImage imageNamed:#"Netherlands"],[UIImage imageNamed:#"Nigeria"],[UIImage imageNamed:#"Portugal"],[UIImage imageNamed:#"Russia"],[UIImage imageNamed:#"South Korea"],[UIImage imageNamed:#"Spain"]];
int random = arc4random_uniform(imageArray.count);
return [imageArray objectAtIndex:random];
}
#end
When you call the -[UITableView reloadData] method you are telling the tableview to refresh ints content based on the source you already gave him, but he doesnt change the source. In some cases you refresh you datasource and you need to refresh the UITableView so you call the -[UITableView reloadData]. What you need to do is to first refresh you data and the refresh the view, so the view uses your new data.
Use the the same way you got the data from your modal to refresh it.
self.blogPost.jsonMutable = [NSMutableArray array];
for (NSDictionary *post in self.blogPost.blogData) {
ARModal *bp = [ARModal blogPostWithHome:[[post objectForKey:#"home"] objectForKey:#"text"]];
bp.away = [[post objectForKey:#"away"] objectForKey:#"text"];
bp.result = [[post objectForKey:#"result"] objectForKey:#"text"];
bp.info = [post objectForKey:#"info"];
bp.homeImage = [[post objectForKey:#"homeimage"] objectForKey:#"src"];
[self.blogPost.jsonMutable addObject:bp];
}
Then execute the -[UITableView reloadData], but now he is going to refresh using the refreshed data that you got from your modal.
If you need something else, comment.
-[UITableView reloadData] doesn't actually reload your data. It tells the table that you've reloaded the data, and now you need the table view to reload.
So before you call reloadData you should do:
self.blogPost.jsonMutable = [NSMutableArray array];
for (NSDictionary *post in self.blogPost.blogData) {
ARModal *bp = [ARModal blogPostWithHome:[[post objectForKey:#"home"] objectForKey:#"text"]];
bp.away = [[post objectForKey:#"away"] objectForKey:#"text"];
bp.result = [[post objectForKey:#"result"] objectForKey:#"text"];
bp.info = [post objectForKey:#"info"];
bp.homeImage = [[post objectForKey:#"homeimage"] objectForKey:#"src"];
[self.blogPost.jsonMutable addObject:bp];
}
Also as this chunk of code only uses information provided by ARModal, you should probably put it in a method in ARModal
While I was surfing over the Internet I've found a lot of examples how to load array in the TableViewController, but none of them helped me!
Couldn't you help me to find what is wrong in my code ?
Thank you in advance!!!
#import "Images.h"
#import "AFNetworking.h"
#import "HTMLparser.h"
#interface Images ()
#end
#implementation Images
#synthesize data;
#synthesize textFromVC1;
#synthesize tableView;
#synthesize so2;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.tableView.delegate = self;
self.tableView.dataSource = self;
self.data = [[NSMutableArray alloc]init];
NSError *error = nil;
NSString *so = [#"http://" stringByAppendingString: self.textFromVC1];
NSURL *url = [[NSURL alloc]initWithString:so];
NSString *str=[[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
HTMLParser *parser = [[HTMLParser alloc] initWithString:str error:&error];
if (error) {
NSLog(#"Error: %#", error);
[parser release];
parser = nil;
return;
}
HTMLNode * body = [parser body];
NSArray *inputs = [body findChildTags:#"img"];
for (HTMLNode *input in inputs) {
NSString *links = [input getAttributeNamed:#"src"];
NSString *so1 = [so stringByAppendingString: #"/"];
so2 = [so1 stringByAppendingString: links];
[self.data addObject:so2];
NSLog(#"%#", data);
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON)
{
}];
[operation start];
}
[self.tableView reloadData];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (void)viewDidUnload
{
[self setTableView:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
// Return the number of sections.
return 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.data.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = #"LinkID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
}
cell.textLabel.text = [self.data objectAtIndex:indexPath.row];
[self.tableView reloadData];
return cell;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
*/
}
- (void)dealloc {
[tableView release];
[super dealloc];
}
#end
well 1) numberOfSections is 0. to see something it should be one IIRC
think thats it but havent double checked
Assuming your data array is built up correctly, your mistake in is your numberOfSections methods. Currently, it returns 0, which tells the UITableView that there are currently no sections to be displayed… ever.
You can either return 1; there or remove the entire method altogether. The default implementation, which you inherit from UITableViewController, also returns 1 by default.
My advice would be to remove the method, as that keeps your own code cleaner. You can always implement it in a later stage, when you might actually need it.
I can parse data and see the output also but I am not able to display them in table view
when I call the view that contain JSON the application is crashed
This is my code:
In the first line of code we define a macro that gives us back a background queue – I like having a kBgQueue shortcut for that, so I can keep my code tighter.
In the second line of code we create a macro named kLatestKivaLoansURL which returns us an NSURL pointing to this URL http://api.kivaws.org/v1/loans/search.json?status=fundraising.
#define kBgQueue dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1
#define kLatestKivaLoansURL [NSURL URLWithString:
#"http://api.kivaws.org/v1/loans/search.json?status=fundraising"] //2
#interface TeacherViewController ()
#end
#implementation TeacherViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
Defined kBGQueue as a macro which gives us a background queue?
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:kLatestKivaLoansURL];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
});
}
#synthesize latestLoans;
#synthesize arrayOfFighterName;
Will be called and the NSData instance will be passed to it. In our case the JSON file is relatively small so we’re going to do the parsing inside fetchedData: on the main thread. If you’re parsing large JSON feeds (which is often the case), be sure to do that in the background.
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
latestLoans = [json objectForKey:#"loans"]; //2
arrayOfFighterName=[[NSMutableArray alloc] init];
//NSLog(#"loans: %#", latestLoans); //3
for( int i = 0; i<[latestLoans count]; i++){
// NSLog(#"%#", [matchListArray objectAtIndex:i]);
arrayOfFighterName[i]=[[latestLoans objectAtIndex:i] objectForKey:#"name"];
// NSLog(#"%#", [arrayOfFighterName objectAtIndex:i]);
}
}
- (void)viewDidUnload
{
[super viewDidUnload];
latestLoans = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
Displaying the result in table view
but unfortunately the result does not display and the app is crashed
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
// Return the number of rows in the section.
return [arrayOfFighterName count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:#"TeacherCell"];
cell.textLabel.text = [arrayOfFighterName objectAtIndex:indexPath.row];
return cell;
// NSLog(#"viewDidLoad is called");
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
*/
}
#end
Change the fetched data method like:
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
latestLoans = [json objectForKey:#"loans"]; //2
arrayOfFighterName=[[NSMutableArray alloc] init];
//NSLog(#"loans: %#", latestLoans); //3
for( int i = 0; i<[latestLoans count]; i++){
// NSLog(#"%#", [matchListArray objectAtIndex:i]);
arrayOfFighterName[i]=[[latestLoans objectAtIndex:i] objectForKey:#"name"];
// NSLog(#"%#", [arrayOfFighterName objectAtIndex:i]);
}
[tableView reloadData];
}
Because the at the first time, the tableView is loaded before the data is added to the array. Due to the asynchronous call. The data is parsed and added to array when the data is retrieved from the server. So you need to reload your tableView to display the data.
Please refer about the asynchronous call in this tutorial.