When i parsing json with tableview everything good when have json items but if not load json items and when i clicked back button gives me this error.
erminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'
*** First throw call stack:
I think json don't load when i clicked fastly back button and gives this error my table view codes under.
#interface MasterViewController ()
#property (nonatomic, assign) NSInteger currentPage;
#property (nonatomic, assign) NSInteger totalPages;
#property (nonatomic, assign) NSInteger totalItems;
#property (nonatomic, assign) NSInteger maxPages;
#property (nonatomic, strong) NSMutableArray *activePhotos;
#property (strong, nonatomic) NSMutableArray *staticDataSource;
#property (nonatomic, strong) NSMutableArray *searchResults;
#property (strong, nonatomic) IBOutlet UITableView *tableView;
#end
- (void)viewDidLoad
{
[super viewDidLoad];
self.activePhotos = [[NSMutableArray alloc] init];
self.searchResults = [[NSMutableArray alloc] init];
self.staticDataSource = [[NSMutableArray alloc] init];
}
#pragma mark - Table View
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.activePhotos.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell;
if (indexPath.row == [self.activePhotos count]) {
cell = [self.tableView dequeueReusableCellWithIdentifier:#"LoadingCell" forIndexPath:indexPath];
UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView *)[cell.contentView viewWithTag:100];
[activityIndicator startAnimating];
} else {
NSDictionary *photoItem = self.activePhotos[indexPath.row];
cell = [self.tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.textLabel.text = [photoItem objectForKey:#"name"];
if (![[photoItem objectForKey:#"description"] isEqual:[NSNull null]]) {
cell.detailTextLabel.text = [photoItem objectForKey:#"description"];
}
}
return cell;
}
- (void)loadPhotos:(NSInteger)page
{
NSString *userismim =[[NSUserDefaults standardUserDefaults] stringForKey:#"userisim"];
NSArray* words = [userismim componentsSeparatedByCharactersInSet :[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString* nospacestring = [words componentsJoinedByString:#""];
NSLog(#"%#",nospacestring);
NSString *apiURL = [NSString stringWithFormat:#"http://bla.com/server/table.php?user=%#",nospacestring];
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:apiURL]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
if (!error) {
NSError *jsonError = nil;
NSMutableDictionary *jsonObject = (NSMutableDictionary *)[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];
NSLog(#"%#",jsonObject);
[self.staticDataSource addObjectsFromArray:[jsonObject objectForKey:#"photos"]];
self.currentPage = [[jsonObject objectForKey:#"current_page"] integerValue];
self.totalPages = [[jsonObject objectForKey:#"total_pages"] integerValue];
self.totalItems = [[jsonObject objectForKey:#"total_items"] integerValue];
self.activePhotos = self.staticDataSource;
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}
}] resume];
}
Thanks for everything . i need your help.
You are showing activity indicator which will keep rotating till json loads.
If you are pressing back button before json loads, what happens is app tries to allocate empty reference to array which is not possible, so it throws an error.
To avoid this, you can stop userInteraction once request goes, and enable only after getting success or failure response.
To disable interaction, add
[[UIApplication sharedApplicaton] beginIgnoringInteractionEvents]
after
NSURLSession *session = [NSURLSession sharedSession];
And to enable again, add :
[[UIApplication sharedApplicaton] endIgnoringInteractionEvents]
before
if (!error) {
This will solve your issue I hope.
Related
enter image description here .Im new to IOS. I am making an app where I want to get data from there in UITableView.
I have seen many blogs and post related to getting data in custom style, but I don't get my answer. I want to show an image in UIImageView and some labels values in label from service. Im using built in service to get data.
There are many post related to static data loading on custom. Can anyone guide how can I load data in my own custom style UItable VIEW FROM SERVICE?
Somewhat I can understand your question.My answer is here
FindHomeViewController.m
#import "FindHomeViewController.h"
#import "DataTableViewController.h"
#interface FindHomeViewController ()
#end
#implementation FindHomeViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)Search:(id)sender {
//Getting response from server
NSDictionary *parameters = #{
#"country": #"UAE",
#"city": #"Dubai",
#"propertytype": #"Office",
#"propertystatus": #"Available",
#"propertyarea" : #"Kanal",
#"minprice" : #"800",
#"maxprice" : #"900"
};
NSData *data = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.pk.house/app_webservices/get_properties.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *dataTask = [session uploadTaskWithRequest: request
fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(data != nil)
{
NSError *parseError = nil;
//If the response is in dictionary format
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSArray *arr=[dictionary valueForKey:#"property_data"];
NSLog(#"arr:%#",arr);
//Updating UIMain Thread
dispatch_async(dispatch_get_main_queue(), ^{
UIStoryboard *sb = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
DataTableViewController *vc = [sb instantiateViewControllerWithIdentifier:#"DataTableViewController"];
vc.arrResprev = [arr mutableCopy];
[self.navigationController pushViewController:vc animated:YES];
});
}
else
NSLog(#"Data returned the parameter is nil here");
}];
[dataTask resume];
}
See my Custom Cell Image View
CustomeCell.h
#import <UIKit/UIKit.h>
#interface CustomCell : UITableViewCell
#property (nonatomic,strong) IBOutlet UILabel *nameLabel;
#property (nonatomic,strong) IBOutlet UILabel *priceLabel;
#property (nonatomic,strong) IBOutlet UILabel *locationLabel;
#property (nonatomic,strong) IBOutlet UIImageView *imgvwRes;
#end
CustomCell.m
#import "CustomCell.h"
#implementation CustomCell
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
#end
DataTableViewController.h
#import <UIKit/UIKit.h>
#interface DataTableViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>
#property (strong, nonatomic) IBOutlet UITableView *tvCustomers;
#property (strong, nonatomic) NSMutableArray *listOfCustomers;
#property (strong, nonatomic) NSMutableArray *arrResprev;
#end
DataTableViewController.m
#import "DataTableViewController.h"
#import "CustomCell.h"
#interface DataTableViewController ()
#end
#implementation DataTableViewController
#synthesize tvCustomers,arrResprev,listOfCustomers;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
listOfCustomers = [[NSMutableArray alloc]init];
listOfCustomers = arrResprev;
[tvCustomers reloadData];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return listOfCustomers.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 134;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell *cell = (CustomCell *)[tvCustomers dequeueReusableCellWithIdentifier:#"cell"];
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil];
if(cell == nil){
cell = nib[0];
}
cell.nameLabel.text = [NSString stringWithFormat:#"%#",[[listOfCustomers objectAtIndex:indexPath.row]objectForKey:#"dealer_name"]];
cell.priceLabel.text = [NSString stringWithFormat:#"%#",[[listOfCustomers objectAtIndex:indexPath.row]objectForKey:#"price"]];
cell.locationLabel.text = [NSString stringWithFormat:#"%#",[[listOfCustomers objectAtIndex:indexPath.row]objectForKey:#"location"]];
NSString *strImgURL = [NSString stringWithFormat:#"%#",[[listOfCustomers objectAtIndex:indexPath.row]objectForKey:#"images"]];
NSError* error = nil;
NSURL *fileURL = [NSURL fileURLWithPath:strImgURL];
NSData* data = [NSData dataWithContentsOfURL:fileURL options:NSDataReadingUncached error:&error];
if (error) {
NSLog(#"%#", [error localizedDescription]);
} else {
NSLog(#"Data has loaded successfully.");
}
UIImage *img = [[UIImage alloc] initWithData:data];
cell.imgvwRes.image = omg;
return cell;
}
For this you need to follow both Appcoda and mikesknowledgebase tutorials .
One shows how to customize UITableViewCell and other shows how to populate UITableView with data fetched from server. You will have to do it in steps.
First, design the Custom UITableViewCell.
Then, follow Mike's tutorial to learn how to set data on cell from API call.
You will use NSURLSession to make API calls.
Follow Link to learn how to make an API call.
Go through these links.
We can only help you in debugging where little amount of code will work. But cannot post code for the complete functionality.
Hope these links will help you.
I have project with normal cell and working success but I want to change it with custom cell I added Cell.h and Cell.m files into my project and I need to integrate custom cell to my working cell. And last I want to show detail view title description and image (I added title codes working) My codes under
Cell.h
#import <UIKit/UIKit.h>
#interface Cell : UITableViewCell
#property (nonatomic, weak) IBOutlet UIImageView *imaj;
#property (nonatomic, weak) IBOutlet UILabel *descriptionLabel;
#property (nonatomic, weak) IBOutlet UILabel *titleLabel;
#end
Cell.m
#import "Cell.h"
#implementation Cell
#synthesize imaj = _imaj;
#synthesize descriptionLabel = _descriptionLabel;
#synthesize titleLabel = _titleLabel;
#end
ViewController.m
#import "MasterViewController.h"
#import "DetailViewController.h"
#import "SDWebImage/UIImageView+WebCache.h"
#import "MBProgressHUD.h"
#import "Cell.h"
static NSString *const kConsumerKey = #"a1SNULSPtp4eLQTsTXKKSgXkYB5H4CMFXmleFvqE";
#interface MasterViewController () <UISearchBarDelegate, UISearchDisplayDelegate,MBProgressHUDDelegate>{
MBProgressHUD *HUD;
}
#property (nonatomic, assign) NSInteger currentPage;
#property (nonatomic, assign) NSInteger totalPages;
#property (nonatomic, assign) NSInteger totalItems;
#property (nonatomic, assign) NSInteger maxPages;
#property (nonatomic, strong) NSMutableArray *activePhotos;
#property (strong, nonatomic) NSMutableArray *staticDataSource;
#property (nonatomic, strong) NSMutableArray *searchResults;
#property (strong, nonatomic) IBOutlet UISearchBar *searchBar;
#property (strong, nonatomic) IBOutlet UITableView *tableView;
#end
#implementation MasterViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.activePhotos = [[NSMutableArray alloc] init];
self.searchResults = [[NSMutableArray alloc] init];
self.staticDataSource = [[NSMutableArray alloc] init];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self loadPhotos:self.currentPage];
}
#pragma mark - Table View
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// if (self.currentPage == self.maxPages
// || self.currentPage == self.totalPages
// || self.currentPage == self.totalPages
// || self.totalItems == self.photos.count) {
// return self.photos.count;
// } else if (self.tableView == self.searchDisplayController.searchResultsTableView){
// return [self.searchResults count];
//
// }
// return self.photos.count + 1;
return self.activePhotos.count + 1;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (self.currentPage != self.maxPages && indexPath.row == [self.staticDataSource count] - 1 ) {
[self loadPhotos:++self.currentPage];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell;
if (indexPath.row == [self.activePhotos count]) {
cell = [self.tableView dequeueReusableCellWithIdentifier:#"LoadingCell" forIndexPath:indexPath];
HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
[self.navigationController.view addSubview:HUD];
HUD.delegate = self;
HUD.labelText = #"Loading";
[HUD showWhileExecuting:#selector(myTask) onTarget:self withObject:nil animated:YES];
} else {
NSDictionary *photoItem = self.activePhotos[indexPath.row];
cell = [self.tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
// cell.textLabel.text = [self.searchResults[indexPath.row] valueForKey:#"name"];
// } else {
// NSDictionary *photoItem = self.photos[indexPath.row];
cell.textLabel.text = [photoItem objectForKey:#"name"];
if (![[photoItem objectForKey:#"description"] isEqual:[NSNull null]]) {
cell.detailTextLabel.text = [photoItem objectForKey:#"description"];
}
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:[photoItem objectForKey:#"image_url"] ] placeholderImage:[UIImage imageNamed:#"placeholder.jpg"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if (error) {
NSLog(#"Error occured : %#", [error description]);
}
}];
}
// NSLog(#"%#",self.searchResults);
return cell;
}
- (void)myTask {
// Do something usefull in here instead of sleeping ...
sleep(1.5);
}
#pragma mark UISearchDisplay delegate
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
// [self.searchResults removeAllObjects];
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:#"SELF.name contains[c] %#", searchText];
self.activePhotos = [NSMutableArray arrayWithArray:[self.staticDataSource filteredArrayUsingPredicate:resultPredicate]];
//[self.tableData filteredArrayUsingPredicate:resultPredicate];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
- (void)loadPhotos:(NSInteger)page
{
NSString *apiURL = [NSString stringWithFormat:#"https://api.500px.com/v1/photos?feature=editors&page=%ld&consumer_key=%#",(long)page,kConsumerKey];
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:apiURL]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
if (!error) {
NSError *jsonError = nil;
NSMutableDictionary *jsonObject = (NSMutableDictionary *)[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];
NSLog(#"%#",jsonObject);
[self.staticDataSource addObjectsFromArray:[jsonObject objectForKey:#"photos"]];
self.currentPage = [[jsonObject objectForKey:#"current_page"] integerValue];
self.totalPages = [[jsonObject objectForKey:#"total_pages"] integerValue];
self.totalItems = [[jsonObject objectForKey:#"total_items"] integerValue];
self.activePhotos = self.staticDataSource;
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}
}] resume];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
DetailViewController *vc = segue.destinationViewController;
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
vc.StoreList = [self.activePhotos objectAtIndex:indexPath.row];
}
#end
Also I uploaded working project here
http://www.filedropper.com/needcustomcell
In your
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
Cell *cell;
// rest of your code
}
that would do it. You have used UITableViewCell you need to replace ot with your custom cell class.
When I scroll down in my tableView some contents of cells disappear (labels and imageViews).
My code:
-(void)viewWillAppear:(BOOL)animated{
[comentarios removeAllObjects];
NSString *lookup=[NSString stringWithFormat:#"http://my.url"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:lookup]];
[request setHTTPMethod:#"GET"];
NSError *error = nil; NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSMutableArray *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#",jsonDict);
for (int i=0; i<[jsonDict count]; i++) {
Comentario *come=[[Comentario alloc] init];
come.nick=[[jsonDict objectAtIndex:i] objectForKey:#"nick"];
come.comment=[[jsonDict objectAtIndex:i] objectForKey:#"content"];
come.avatar=[[jsonDict objectAtIndex:i] objectForKey:#"color"];
[comentarios addObject:come];
}
[self reloadInputViews];
[self.comentariosTableView reloadData];
}
and
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
if( cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier: CellIdentifier];
}
// Display recipe in the table cell
UIImageView *avatar = (UIImageView *)[cell viewWithTag:100];
avatar.image = [UIImage imageNamed:[[comentarios objectAtIndex:indexPath.row] avatar]];
UILabel *nick = (UILabel *)[cell viewWithTag:101];
nick.text =[[comentarios objectAtIndex:indexPath.row] nick];
UILabel *comment = (UILabel *)[cell viewWithTag:102];
comment.text = [[comentarios objectAtIndex:indexPath.row] comment];
UIButton *sinvoto = (UIButton *)[cell viewWithTag:103];
UIButton *ticket = (UIButton *)[cell viewWithTag:104];
return cell;
}
I can't see the mistake, please help me.
Thank you in advance
EDIT Nª1
just changed this
ViewController.m
#import "ViewController.h"
#import "SimpleTableCell.h"
#interface ViewController (){
NSMutableArray *comentarios;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.comenatrioTableView.delegate=self;
self.comenatrioTableView.dataSource=self;
self.automaticallyAdjustsScrollViewInsets = NO;
UIImage *plus=[[UIImage imageNamed:#"megafono.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithImage:plus style:UIBarButtonItemStylePlain target:self action:#selector(comenta:)];
self.navigationController.navigationBar.barTintColor=[UIColor colorWithRed:204.0/255.0 green:0.0/255.0 blue:00.0/255.0 alpha:1.0f];
comentarios=[[NSMutableArray alloc] init];
[self reloadInputViews];
}
-(void)viewWillAppear:(BOOL)animated{
[comentarios removeAllObjects];
NSString *lookup=[NSString stringWithFormat:#"http://myURL"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:lookup]];
[request setHTTPMethod:#"GET"];
NSError *error = nil; NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSMutableArray *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#",jsonDict);
for (int i=0; i<[jsonDict count]; i++) {
Comentario *come=[[Comentario alloc] init];
come.nick=[[jsonDict objectAtIndex:i] objectForKey:#"nick"];
come.comment=[[jsonDict objectAtIndex:i] objectForKey:#"content"];
come.avatar=[[jsonDict objectAtIndex:i] objectForKey:#"color"];
[comentarios addObject:come];
}
[self reloadInputViews];
}
-(void)viewDidAppear:(BOOL)animated{
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [comentarios count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 110;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableCell";
SimpleTableCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier forIndexPath:indexPath];
Comentario *comentario=[[Comentario alloc] init];
comentario =[comentarios objectAtIndex:indexPath.row];
cell.avatar.image=[UIImage imageNamed:[comentario avatar]];
cell.nick.text=[comentario nick];
cell.comment.text =[comentario comment];
return cell;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
-(void)comenta:(id)sender{
[self performSegueWithIdentifier:#"goComment" sender:self];
}
#end
and ViewController.h
#import <UIKit/UIKit.h>
#import "Comentario.h"
#interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
#property (weak, nonatomic) IBOutlet UITableView *comenatrioTableView;
#end
Edit Nª3
The proble is when I scroll down, the information of cells become nil but comentarios Array have the information.
Edit Nª4
here is the project https://github.com/QuimeraKoke/BANG-
I have a couple of other suggestions that will improve your code.
You have to call super in viewDidAppear and viewWillAppear methods:
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:YES];
}
Instead of using:
Comentario *comentario = [[Comentario alloc] init];
comentario = [comentarios objectAtIndex:indexPath.row];
with:
Comentario *comentario = [comentarios objectAtIndex:indexPath.row];
Finally, you should check your dataSource:
for (int i=0; i<[jsonDict count]; i++) {
Comentario *come = [[Comentario alloc] init];
come.nick = [[jsonDict objectAtIndex:i] objectForKey:#"nick"];
come.comment = [[jsonDict objectAtIndex:i] objectForKey:#"content"];
come.avatar = [[jsonDict objectAtIndex:i] objectForKey:#"color"];
[comentarios addObject:come];
NSLog(#"nick = %#, comment = %#, avatar = %#", come.nick, come.comment, come.avatar);
}
EDIT:
Instead of using:
#interface Comentario : NSObject
#property (weak,nonatomic) NSString *nick;
#property (weak,nonatomic) NSString *comment;
#property (weak,nonatomic) NSString *avatar;
#end
you should use:
#interface Comentario : NSObject
#property (copy,nonatomic) NSString *nick;
#property (copy,nonatomic) NSString *comment;
#property (copy,nonatomic) NSString *avatar;
#en
Your problem has been resolved.
Copy
copy is required when the object is mutable. Use this if you need the
value of the object as it is at this moment, and you don't want that
value to reflect any changes made by other owners of the object. You
will need to release the object when you are finished with it because
you are retaining the copy.
Weak
weak is similar to strong except that it won't increase the reference
count by 1. It does not become an owner of that object but just holds
a reference to it. If the object's reference count drops to 0, even
though you may still be pointing to it here, it will be deallocated
from memory.
This is a good website to learn about strong and weak for iOS 5.
http://www.raywenderlich.com/5677/beginning-arc-in-ios-5-part-1
In addition to the above problem,your constrains of the SimpleTableCell is also incorrect:
You should go to the Main.storyboard and check it.(In Interface Builder Select the Compact Width and Compact Height Size Class)
The tableView:cellForRowAtIndexPath: code you're using is pretty old.
I'd suggest creating a custom UITableViewCell class, with properties for your labels, image, and buttons.
#interface MyTableViewCell : UITableViewCell
#property (nonatomic, weak) IBOutlet UILabel *nick;
#property (nonatomic, weak) IBOutlet UILabel *comment;
#property (nonatomic, weak) IBOutlet UIImageView *avatar;
#property (nonatomic, weak) IBOutlet UIButton *sinvoto;
#property (nonatomic, weak) IBOutlet UIButton *ticket;
#end
In your storyboard, set that cell's class to your custom tableViewCell, and connect its IBOutlets to the storyboard cell's labels, image, and buttons. This will eliminate having to use tags.
Change the dequeueReusableCellWithIdentifier: call to:
MyTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
This will always return a cell, so you will never have to check for nil.
Now you can directly set the cell's properties:
cell.avatar.image = [UIImage imageNamed:[[comentarios objectAtIndex:indexPath.row] avatar]];
cell.nick.text =[[comentarios objectAtIndex:indexPath.row] nick];
cell.comment.text = [[comentarios objectAtIndex:indexPath.row] comment];
Update:
This line (has to do with changing the keyboard) is unnecessary and can be removed:
[self reloadInputViews];
Is there a reason why you are using a UIViewController (with a tableView that you added), instead of simply using a UITableViewController?
The UITableViewController knows how to adjust its insets to account for top and bottom bars (and you would set its automaticallyAdjustsScrollViewInsets to YES).
After making the changes that Banning suggests, you may be ok. I can't see any other reason why the cells would be blank after scrolling.
If it's still happening, you should post your Comentario class, so we can see if an issue with that code is affecting the stored data.
I'm trying to make an item feed with a UITableView and some JSON objects,
but when I try filling an instance of my custom cell with the JSON data, the UILabels won't change their text.
The JSON has been tested and works. It goes through the loop and creates the right amount of rows. But the text isn't changing to the text from the JSON file.
Here's my code:
feed.m
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *FeedURL = [NSURL URLWithString:#"http://www.personeelsapp.jordivanderhek.com/company/bijcasper/nieuws.json"];
NSData *jsonData = [NSData dataWithContentsOfURL:FeedURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#", dataDictionary);
self.posts = [NSMutableArray array];
PostsArray = [dataDictionary objectForKey:#"feed"];
for (NSDictionary *bpdDictionary in PostsArray) {
// make new post object
FeedPosts *posts = [FeedPosts InitPost];
NSLog(#"feed check %#" ,[bpdDictionary objectForKey:#"name"]);
posts.postTitle = [bpdDictionary objectForKey:#"name"];
posts.postProfilepic = [bpdDictionary objectForKey:#"profilePic"];
posts.postDatum = [bpdDictionary objectForKey:#"timeStamp"];
posts.postMessage = [bpdDictionary objectForKey:#"status"];
posts.postImage = [bpdDictionary objectForKey:#"image"];
[self.posts addObject:posts];
}
}
[…]
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section {
return [self.posts count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *Cellindentifier = #"PostCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Cellindentifier forIndexPath:indexPath];
// Configure the cell...
FeedPosts *posts = [self.posts objectAtIndex:indexPath.row];
cell.postTitle.text = #"test title";
cell.postDatum.text = posts.postDatum.text;
cell.postMessage.text = posts.postMessage.text;
return cell;
}
}
FeedPosts.h
#property (strong, nonatomic) IBOutlet UILabel *postTitle;
#property (strong, nonatomic) IBOutlet UILabel *postMessage;
#property (strong, nonatomic) IBOutlet UIImageView *postImage;
#property (strong, nonatomic) IBOutlet UIImageView *postProfilepic;
#property (strong, nonatomic) IBOutlet UILabel *postDatum;
// designated init
+ (id) InitPost;
FeedPosts.m
+ (id) InitPost {
// init new feed item
return [[self alloc]init];
}
have been getting the following error:
-[__NSCFString text]: unrecognized selector sent to instance
What am I doing wrong?
You have declared several UILabels in FeedPosts.
#property (strong, nonatomic) IBOutlet UILabel *postTitle;
In the following code, you assign NSString (text) to the label object:
FeedPosts *posts = [FeedPosts InitPost];
NSLog(#"feed check %#" ,[bpdDictionary objectForKey:#"name"]);
posts.postTitle = [bpdDictionary objectForKey:#"name"];
Instead, you should set the text for those labels:
posts.postTitle.text = [bpdDictionary objectForKey:#"name"];
Same goes for postMessage and postDatum.
My ParseXML method reads the value of NSNumber, which can be incremented by a click of a button.
My ParseXML method has 240 objects, each 8 have an ID from 1 to 30.
The idea is that if i increment the NSNumber from 1 to 2, it refreshes my view and grabs the 8 objects that match the ID and displays it in my view.
That is exactly what is not doing.
.h
#interface FixturesController : UITableViewController
{
NSMutableData *_responseDataFixtures;
int goUp;
NSNumber *test;
}
#property (nonatomic, retain) NSArray *tableDataFixtures;
#property (nonatomic, strong) NSMutableArray *roundParser;
#property (nonatomic, strong) NSString *seasonRoundString;
#property (nonatomic, strong) NSNumber *seasonRoundNumber;
- (IBAction)goUpByOne:(UIButton *)sender;
-(void) parseXMLFixtures:(NSNumber *) giveME;
#end
.m
- (void) viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self parseXMLFixtures:#2];
}
- (void)viewDidLoad
{
[super viewDidLoad];
goUp = 1;
test = [NSNumber numberWithInt:goUp];
}
// this allows me to increment the count of NSNumber.
- (IBAction)goUpByOne:(UIButton *)sender {
goUp++;
test = [NSNumber numberWithInt:goUp];
goUp = [test intValue];
}
-(void) parseXMLFixtures:(NSNumber *) giveME
{
giveME = test;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"There's no going back"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *xmlString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *xml = [NSDictionary dictionaryWithXMLString:xmlString];
NSMutableArray *items = [xml objectForKey:#"Match"];
NSMutableArray *newFixtureObjectArray = [[NSMutableArray alloc] init];
NSNull *nullValue = [NSNull null];
[newFixtureObjectArray insertObject:nullValue atIndex:0];
[newFixtureObjectArray insertObject:nullValue atIndex:1];
for (NSDictionary *dict in items) {
FixturesObject *myFixtures = [FixturesObject fixtureFromXMLDictionary:dict];
[newFixtureObjectArray addObject:myFixtures];
}
///////
_seasonRoundString = [NSString stringWithFormat:#"%d", [giveME intValue]];
_roundParser = [[NSMutableArray alloc]init];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"round == %#", _seasonRoundString];
NSArray *filteredArray = [newFixtureObjectArray filteredArrayUsingPredicate:predicate];
_roundParser = [NSMutableArray arrayWithArray:filteredArray];
[_roundParser insertObject:nullValue atIndex:0];
NSLog(#" Objects of Fixtures in my array %#", _roundParser);
/////
[self setTableDataFixtures:_roundParser];
}
Any suggestions? Thank you. I really need this to work so i can go sleep ˆˆ
Have you impleted the UITableViewDelegate, UITableViewDataSource methods yet?
The methods are:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{ }
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { }
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{}
You can follow this tutorial