load local json information in UITableView - objective-c

I have my own json file "list.json" for a list of sample informations like below. My json file is
located inside of Xcode, I want to show my information to the table, would you please give me some hints and help for this implementation, how can I parse local json and load information in table.
[
{
"number": "1",
"name": "jon"
},
{
"number": "2",
"name": "Anton"
},
{
"number": "9",
"name": "Lili"
},
{
"number": "7",
"name": "Kyle"
},
{
"display_number": "8",
"name": "Linda"
}
]

you can create a custom class which inherits from UITableViewController.
The code to read the contents of list.json file into an array is:
NSString * filePath =[[NSBundle mainBundle] pathForResource:#"list" ofType:#"json"];
NSError * error;
NSString* fileContents =[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
if(error)
{
NSLog(#"Error reading file: %#",error.localizedDescription);
}
self.dataList = (NSArray *)[NSJSONSerialization
JSONObjectWithData:[fileContents dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:NULL];
And the header file is:
#import <UIKit/UIKit.h>
#interface TVNA_ReadingDataTVCViewController : UITableViewController
#end
The implementation is:
#import "TVNA_ReadingDataTVCViewController.h"
#interface TVNA_ReadingDataTVCViewController ()
#property NSArray* dataList;
#end
#implementation TVNA_ReadingDataTVCViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self readDataFromFile];
[self.tableView reloadData];
}
-(void)readDataFromFile
{
NSString * filePath =[[NSBundle mainBundle] pathForResource:#"list" ofType:#"json"];
NSError * error;
NSString* fileContents =[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
if(error)
{
NSLog(#"Error reading file: %#",error.localizedDescription);
}
self.dataList = (NSArray *)[NSJSONSerialization
JSONObjectWithData:[fileContents dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:NULL];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.dataList.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
id keyValuePair =self.dataList[indexPath.row];
cell.textLabel.text = keyValuePair[#"name"];
cell.detailTextLabel.text=[NSString stringWithFormat:#"ID: %#", keyValuePair[#"number"]];
return cell;
}
#end
Finally, on your story board, assign this class as the custom class of your Table View Controller. Hope this helps.

Related

Empty UITableViewController with async calls

I am working on using NSURLSession and JSON serialization to fetch content from my site. The async calls and getting the JSON data work perfectly. My issue is, when it comes to displaying the data in the TableviewController, I put an NSLog statement to see if there is data and there is, but that cell.textlable.text never updates. I'm guessing the issue is the threads but I can't figure it out. Can you help?
#interface MainTableViewController :
UITableViewController<LokalModelProtocol>
#property (strong,nonatomic) NSMutableArray* arr;
#end
#implementation MainTableViewController
#synthesize arr;
- (void)viewDidLoad {
[super viewDidLoad];
arr = [[NSMutableArray alloc]init];
LokalModel *lokal = [[LokalModel alloc]init];
lokal.delegate=self;
[lokal downloadItems];
}
-(void)itemsDownloaded:(NSMutableArray *)items
{
arr=items;
//NSLog(#"%#", items);
[self.tableView reloadData];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section {
#warning Incomplete implementation, return the number of rows
// return 1;
return [arr count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"mainCell" forIndexPath:indexPath];
PostModel *post = [[PostModel alloc]init];
post =[arr objectAtIndex:indexPath.row];
NSLog(#"%#", post.postTitle); ////this outputs the correct strings///////
cell.textLabel.text =[NSString stringWithFormat:#"%#", post.postTitle];
cell.detailTextLabel.text = post.postTitle;///neither of these do//////
return cell;
}
#end
#protocol LokalModelProtocol <NSObject,NSURLSessionDelegate>
+(void)itemsDownloaded:(NSMutableArray*)items;
#end
#interface LokalModel : NSObject
-(void)downloadItems;
#property (strong, nonatomic) NSMutableData* thedata;
#property (strong, nonatomic) NSString* urlString;
#property (strong, nonatomic) NSURL* theUrl;
#property (strong,nonatomic) id<LokalModelProtocol>delegate;
+(void)parseJson:(NSData*)data;
#end
id<LokalModelProtocol>delegate;
#implementation LokalModel;
#synthesize thedata,urlString,theUrl,delegate;
-(void)downloadItems{
NSURL *theUrl = nil;
static NSString* urlString = #"https://balalatet.com/wp-json/wp/v2/posts";
theUrl=[NSURL URLWithString:urlString];
NSURLSession *currentSession= [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionDataTask *task = [currentSession dataTaskWithURL:theUrl completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error){
[NSException raise:#"error" format:#"%#",error.localizedDescription];
NSLog(#"error1");
}
else{
NSLog(#"success");
[LokalModel parseJson:data];
}
}];
[task resume];
}
+(void)parseJson:(NSData*)data{
NSArray *jsonResults = [[NSArray alloc]init];
NSError *jsonerror;
jsonResults =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonerror];
if (jsonerror)
[NSException raise:#"json error" format:#"%#",jsonerror.localizedDescription];
NSMutableArray *posts = [[NSMutableArray alloc] init];
NSMutableDictionary *jsonElenent =[NSMutableDictionary dictionary];
for (NSMutableDictionary *d in jsonResults)
{
jsonElenent=d;
PostModel *thePost=[[PostModel alloc]init];
thePost.postId= jsonElenent[#"id"];
thePost.postDate= jsonElenent[#"date"];
thePost.postDategmt= jsonElenent[#"date_gmt"];
thePost.postGuid= jsonElenent[#"guid"];
thePost.postSlug= jsonElenent[#"slug"];
thePost.postStatus= jsonElenent[#"status"];
thePost.postSticky= jsonElenent[#"sticky"];
thePost.postPingStatus= jsonElenent[#"ping_status"];
thePost.postType= jsonElenent[#"type"];
thePost.postCommentStatus= jsonElenent[#"comment_status"];
thePost.postTags= jsonElenent[#"tags"];
thePost.postTitle= jsonElenent[#"title"];
thePost.postTemplate= jsonElenent[#"template"];
thePost.postLink= jsonElenent[#"link"];
thePost.postMeta= jsonElenent[#"meta"];
thePost.postModified= jsonElenent[#"modified"];
thePost.postModifiedgmt= jsonElenent[#"modified_gmt"];
thePost.postFeaturedMedia= jsonElenent[#"featured_media"];
thePost.postFormat= jsonElenent[#"format"];
thePost.postLinks= jsonElenent[#"links"];
thePost.postAuthor= jsonElenent[#"author"];
thePost.postContent= jsonElenent[#"content"];
thePost.postCategory= jsonElenent[#"category"];
thePost.postExcerpt= jsonElenent[#"excerpt"];
NSLog(#"%#", thePost.postTitle);
[posts addObject:thePost];
}
dispatch_async(dispatch_get_main_queue(), ^{
[delegate itemsDownloaded:posts];
});
}
#end
Update
my apologies as part of my debugging info is incorrect. the nslog output did not come from the cellForRowAtIndexPath method. in fact the arr array remains empty because the
(void)itemsDownloaded:(NSMutableArray *)items
is never called. im sure i setup the protocol correctly. any thoughts on why the MainTableViewControllerClass cant get the data?
update
so i realized that i forgot to remove the line
id<LokalModelProtocol>delegate;
that i put right before the #implementation in LokalModel. but now doing so causes an error "unrecognized selector sent to instance" at the line
[delegate itemsDownloaded:posts];
I aslo tried
[self.delegate itemsDownloaded:posts];
but it throws the same exception.
Solved
My protocol method had to be an instance method, and i had it set as a class method.
Before return your cell add try to add this code in cellForRowIndexPath
[cell layoutIfneeded];
I believe you have to add a registerNib:forCellReuseIdentifier: or registerClass:forCellReuseIdentifier: prior to using dequeueReusableCellWithIdentifier:forIndexPath: (in viewDidLoad for example)
From the documentation: https://developer.apple.com/documentation/uikit/uitableview/1614878-dequeuereusablecellwithidentifie?language=objc
Important
You must register a class or nib file using the registerNib:forCellReuseIdentifier: or registerClass:forCellReuseIdentifier: method before calling this method.

Array reduplication not working

Xcode problem. I have a nsmutablearray that is pulling json objects. Example Company: Name, state, address, phone number, etc.
I am pulling the info just fine. And I want to display 1 of each state in a table view. It works fine but shows multibles of the same state. But I only want to show 1 of each state. I am using some code but it does not return any states. I have seen a lot of examples and this should work but it returns nothing. If I skip this code below it does show all states. i have also tried a for loop. And tried array to NSSet. Nothing is working. Any Ideas???
My problem is with this code...
//Create states only array...remove duplicate states here
NSArray *statesArray = [companies valueForKeyPath:#"#distinctUnionOfObjects.state"];
return statesArray;
Here is my whole code. Please help been struggling with this for a week.
#interface StatesTableViewController ()
#property (nonatomic) NSString *name;
#property (nonatomic) NSString *state;
#end
#implementation StatesTableViewController
NSArray *companies;
NSArray *statesArray;
- (void)viewDidLoad {
[super viewDidLoad];
NSString *address = #"http://www.companiesFeed";
NSURL *url = [[NSURL alloc] initWithString:address];
//laod the data on a background queue..
//if we were connecting to a an online url then we need it
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
companies = [self readCompanies:url];//, statesSet = [self readCompanies:url];
//now that we have the data, reload the table data on the main ui thread
[self.tableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:YES];
});
}
//new code
- (NSArray *)readCompanies:(NSURL *)url {
//create a nsurlrequest with the given Url
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:
NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30.0];
//get the data
NSURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
//now create a nsdictionary from the json data
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data
options:0 error:nil];
//create a new array to hold the comanies
NSMutableArray *companies = [[NSMutableArray alloc] init];
//get an array of dictionaries with the key "company"
NSArray *array = [jsonDictionary objectForKey:#"companies"];
//iterate throught the array of dictionaries
for (NSDictionary *dict in array) {
//create a new company object with information in the dictionary
Company *company = [[Company alloc] initWithJSONDictionary:dict];
//add the Company object to the array
[companies addObject:company ];
}
//Create states only array...remove duplicate states here
NSArray *statesArray = [companies valueForKeyPath:#"#distinctUnionOfObjects.state"];
return statesArray;
//return companies;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark -table view controller methods
//change uniqueValue errors to companies
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger) section {
//return[companies count];
return [statesArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellID = #"CellIDState";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellID];
if (cell == nil){
//single line on table view
//cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
// dual line on table view
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
}
//edit single state
//Company *company = [companies objectAtIndex:indexPath.row];
Company *company = [statesArray objectAtIndex:indexPath.row];
//cell.textLabel.text = company.company_id;
cell.textLabel.text = company.state;
cell.detailTextLabel.text = [NSString stringWithFormat:#"%#",company.companyName];
//adds cheveron to tableviewl
[cell setAccessoryType: UITableViewCellAccessoryDisclosureIndicator];
return cell;
}
#pragma mark - navigation
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
}
#end
I was able to get the unique list of states by using a predicate and a block to check a set for existing states. Like so:
NSMutableArray *statesArray = [NSMutableArray array];
[companies filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
Company *dict = (Company *)evaluatedObject;
BOOL seen = [statesArray containsObject:dict];
if (!seen) {
[statesArray addObject:dict];
}
return !seen;
}]];
NSLog(#"unique states: %#", statesArray);
Where the companies array looks like this:
{[{
"company_id": "22",
"entityformSubmissionID": "22",
"companyName": "house of waffles",
"companySlogan": " where your home is!",
"address1": "123 here",
"address2": "thre",
"city": "everywhere",
"state": "CA",
"zipCode": "94531",
"phoneNumber": "777-777-7777",
"email": "test#test.com",
"additionalCompanyInfo": "all additional company info is going here",
"sales": "There are no sales!",
"rentalTerms": "Terms is dont break our stuff jerks!",
"companyLogo": "/16x16icon.png"
}]

Load JSON data into table view using Xcode 4.6

I'm trying to load a data from a JSON file. I've added this file to my Project Files in Xcode 4.6, but every time I run my code, I get empty cells in the TableView, with no data at all, even though I've declared a properly for each label and assigned a value for them from the JSON file.
I have created two classes: events.h and .m, jsonloader.h and .m, and imported them into my main view controller.
Here's a sample of my JSON data:
{
"Events": [
{
"id": "1",
"title": "parr jazz presents zoe chiotis",
"performingArtists": "Zoe Chiotis",
"day": "Tuesday",
"date": "2013-12-03",
"lastUpdated": "2013-12-03",
"startingTime": "8:00:00 PM",
"endingTime": "1:00:00 AM",
"venue": "STUDIO2",
"location": {
"streetAddress": "33-45 Parr Street",
"postCode": "L1 4JN"
},
"music genre": "Jazz",
"information": "ZOE CHIOTIS is a singer/songwriter/guitarist based in Manchester. ",
"image": "http://bandonthewall.org/images/content/large/zoe-chiotis-1764.jpg",
"thumb": "http://swingbands.co.uk/wp-content/zoechiotis.jpg"
},
...
]}
This is event.m:
#implementation JSONLoader
- (NSArray *)eventsFromJSONFile:(NSURL *)url {
// Create a NSURLRequest with the given URL
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:30.0];
// Get the data
NSURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
// Now create a NSDictionary from the JSON data
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
// Create a new array to hold the locations
NSMutableArray *events = [[NSMutableArray alloc] init];
// Get an array of dictionaries with the key "Events"
NSArray *array = [jsonDictionary objectForKey:#"Events"];
// Iterate through the array of dictionaries
for(NSDictionary *dict in array) {
// Create a new event object for each one and initialise it with information in the dictionary
Events *dataevents = [[Events alloc] initWithJSONDictionary:dict];
// Add the Location object to the array
[events addObject:dataevents];
}
// Return the array of Location objects
return events;
}
and in my mainViewController.m I included this:
#implementation MV_HomeViewController {
NSArray *_events;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
// Create a new JSONLoader with a local file URL
JSONLoader *jsonLoader = [[JSONLoader alloc] init];
NSURL *url = [[NSBundle mainBundle] URLForResource:#"EventsData" withExtension:#"json"];
// Load the data on a background queue...
// As we are using a local file it's not really necessary, but if we were connecting to an online URL then we'd need it
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
_events = [jsonLoader eventsFromJSONFile:url];
// Now that we have the data, reload the table data on the main UI thread
[self.myTableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:YES];
});
}
#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 [_events count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"eventCell";
MV_CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier
forIndexPath:indexPath];
if (cell == nil) {
cell = [[MV_CustomCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
// Configure the cell...
//[[cell textLabel] setText:_eventType];
Events *event = [_events objectAtIndex:indexPath.row];
cell.TitleLabel.text = event.title;
cell.GenreLabel.text = event.musicGenre;
return cell;
}
Does anybody know what the problem is here?

Multilevel JSON Dictionary - can't extract key into new dictionary

I've been stuck on a problem for a few days now. I have searched the internet and found many answers, but nothing that seems to work - I may not grasp how to modify my own code.
I have a JSON connection which I make a dictionary. This all works very well when I dont have a multilevel dictionary, but as soon as I have:
{
"Table": [
{
"MENUID": 1072.0,
"MENUDESC": "HOME ",
"PARENTMENUID": null,
"NAVIGATETO": "content.aspx?item=1072&pid=0",
"NAVIGATETO2": "default.aspx?item=1072&pid=0",
"PROTECTED": null,
"parentmenuid2": null
},
{
"MENUID": 1073.0,
"MENUDESC": "PRODUCTS & SERVICES",
"PARENTMENUID": null,
"NAVIGATETO": "#",
"NAVIGATETO2": "default.aspx?item=1073&pid=0",
"PROTECTED": null,
"parentmenuid2": null
}
]
}
I adapt my code as follows:
- (void)fetchTweets
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString: #"http://adhoc.nyxtek.co.za/spfjsonws/default2.aspx"]];
NSError* error;
menuItems = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
NSArray * allKeys = [menuItems allKeys];
NSLog(#"Count : %d", [allKeys count]);
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
});
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return menuItems.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 = (NSDictionary *)[menuItems objectForKey:#"Table"];
NSArray * allKeys = [tweet allKeys];
NSLog(#"Count : %d", [allKeys count]);
//NSDictionary *tweet = [tweets objectAtIndex:indexPath.row];
NSString *text = [tweet objectForKey:#"MENUDESC"];
NSString *name = [tweet objectForKey:#"MENUID"];
cell.textLabel.text = text;
cell.detailTextLabel.text = [NSString stringWithFormat:#"by %#", name];
return cell;
}
Specifically this line of code is not working:
NSDictionary *tweet = (NSDictionary *)[menuItems objectForKey:#"Table"];
My first count of the outer dictionary is 1 which is correct, but my second count of the new above dictionary is 0 which is wrong.
I have applied much of this from researching previous questions as I understand the importance of research, but I still cant seem to find a specific fault.
Any assistance would be appreciated.
Table is an array (of dictionaries):
"Table": [
...
]
So the code should be:
NSArray *tweet = (NSArray *)[menuItems objectForKey:#"Table"];

UItableviewcontroller cell text label content not displayed

I ve successfully parsed json file in my app but when i tried to display all it in table view its not getting displayed .here is my code.
NSString *urlstr=[NSString stringWithFormat:#"http://minora.p41techdev.net/portal.php"];
NSURL *url=[NSURL URLWithString:urlstr];
NSData *data =[NSData dataWithContentsOfURL:url];
NSError *error;
NSArray *json=(NSMutableArray*) [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
//NSLog(#"%#",json);
NSDictionary *dict =[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:#"a title", #"more data",nil] forKeys:[NSArray arrayWithObjects:#"titleKey",#"dataKey", nil]];
NSLog(#"1");
NSString *integ = [dict valueForKey:#"id"];
NSString *title=[dict valueForKey:#"title"];
NSString *category=[dict valueForKey:#"category"];
NSString *description=[dict valueForKey:#"description"];
NSString *spectitle=[dict valueForKey:#"spectitle"];
NSString *specvalue=[dict valueForKey:#"specvalue"];
NSArray *arr =[NSArray arrayWithObjects:integ,title,category,description,spectitle,specvalue, nil];
[tablearray addObject:arr];
NSLog(#"%#",tablearray);
}
- (void)viewDidUnload
{
[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)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//#warning Incomplete method implementation.
// Return the number of rows in the section.
return [tablearray count];
NSLog(#"5");
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.textLabel.text=[[tablearray objectAtIndex:indexPath.row] objectAtIndex:1];
return cell;
}
and my json file looks like this
[
{
"id": "1",
"category": "New Category1",
"title": "New Product2",
"description": "Please type a description1",
"imgurl": "http://s.wordpress.org/about/images/wordpress-logo-notext-bg.png",
"spectitle": "Specification",
"specvalue": "Value"
},
{
"id": "2",
"category": "Mobile",
"title": "Samsung",
"description": "Please type a description",
"imgurl": "http://s.wordpress.org/about/images/wordpress-logo-notext-bg.png",
"spectitle": "Price",
"specvalue": "100$"
}
]
Guidance please...
i'm getting thread issue like this
2012-07-20 19:36:03.504 tablevc[2253:f803] 1
2012-07-20 19:36:03.505 tablevc[2253:f803] 2
2012-07-20 19:36:03.507 tablevc[2253:f803] 4
2012-07-20 19:36:03.507 tablevc[2253:f803] 3
2012-07-20 19:36:03.508 tablevc[2253:f803] *** Assertion failure in -[UITableView _createPreparedCellForGlobalRow:withIndexPath:], /SourceCache/UIKit_Sim/UIKit-1914.84/UITableView.m:6061
2012-07-20 19:36:03.508 tablevc[2253:f803] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'
*** First throw call stack:
(0x13d2022 0x1563cd6 0x137aa48 0x9b32cb 0xb6d28 0xb73ce 0xa2cbd 0xb16f1 0x5ad21 0x13d3e42 0x1d8a679 0x1d94579 0x1d194f7 0x1d1b3f6 0x1d1aad0 0x13a699e 0x133d640 0x13094c6 0x1308d84 0x1308c9b 0x12bb7d8 0x12bb88a 0x1c626 0x2ae2 0x2a55 0x1)
terminate called throwing an exception
I don't see the initialization of tablearray anywhere.
Add this to your viewDidLoad method:
tablearray = [[NSMutableArray alloc] init];
I also see that you're inserting an array within an array. This means that when you need to access the correct data (NSString in your case), you must use the correct index:
cell.textLabel.text=[[tablearray objectAtIndex:indexPath.row] objectAtIndex:1];
I used "objectAtIndex:1" because the title string is stored at index 1 in the inner array. A better, more generic approach would be to use NSDictionary. For example:
NSDictionary *dict =[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:#"a title", #"more data",nil] forKeys:[NSArray arrayWithObjects:#"titleKey",#"dataKey"]];
Also, make sure your delegate returns the correct amount of sections for your table.
Number of sections in tableview is at least one...
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;//It should be at least one.......
}
Write the following code in cellForRowAtIndexPath: method. Otherwise you will get error.
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
I think it will be helpful to you.
call [tableView reloadData] after you add arr in your table array...
[tablearray addObject:arr];
[tableView reloadData]
NSLog(#"2");
hope it helps
You should initialize the cell like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
[[cell textLabel] setText:[tablearray objectAtIndex:indexPath.row]];
// Configure the cell...
return cell;
}
You have tablarray with 1 element. This element is an array containing a few entries.
Your data source declares only one cell (tablearray count, which is one).
Your cellForIndexPath method will always look for the first and only the first element in the json array anyway.
Edit: unrelated, but if a field in your json is not set, you'll get nil back, and that'll terminate your array in arrayWithObjects, which will likely cause an out of bounds index down the line.
Be very careful with this method, it's very easy to shoot yourself in the foot with it.