UITableView taking lots of time to bind data - ios

I am using UITableView and after calling web service I am creating cells and binding data. Web service fetching data speed is very good and fast but i checked it's taking time to bind cells to UITableView.My code is -
.m file
#pragma mark tableViewDelegate Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//return ([team1Arr count]+1);
if (isFiltered) {
return [filteredMySquareArr count];
}
else
return [mySquareArr count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:nil];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
// dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
UILabel *squareNameLbl = [[UILabel alloc] initWithFrame:CGRectMake(25.0, 7.0, 300, 25)];
[squareNameLbl setFont:[UIFont systemFontOfSize:15]];
UILabel *descLbl = [[UILabel alloc]initWithFrame:CGRectMake(25.0, 32.0, 285.0, 13.0)];
[descLbl setFont:[UIFont systemFontOfSize:12]];
descLbl.textColor = [UIColor colorWithRed:72.0f/255 green:180.0f/255 blue:71.0f/255 alpha:1.0f];
UIImageView *lockImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 15, 10, 10)];
NSString *accessTypeStr;
if (isFiltered) {
//cell.textLabel.text = [filteredMySquareArr objectAtIndex:indexPath.row];
squareNameLbl.text = [filteredMySquareArr objectAtIndex:indexPath.row];
descLbl.text =[NSString stringWithFormat:#"Located within %.2f miles", [[filteredMySquareDescArr objectAtIndex:indexPath.row] doubleValue]];
accessTypeStr = [NSString stringWithFormat:#"%#",[filteredAccessTypeArr objectAtIndex:indexPath.row]];
if ([accessTypeStr isEqualToString:#"private"]) {
lockImage.image = [UIImage imageNamed:#"lock.png"];
}
}
else
{
//cell.textLabel.text = [mySquareArr objectAtIndex:indexPath.row];
squareNameLbl.text = [mySquareArr objectAtIndex:indexPath.row];
descLbl.text =[NSString stringWithFormat:#"Located within %.2f miles",[[mySquareDescArr objectAtIndex:indexPath.row] doubleValue]];
accessTypeStr = [NSString stringWithFormat:#"%#",[accessTypeArr objectAtIndex:indexPath.row]];
if ([accessTypeStr isEqualToString:#"private"]) {
lockImage.image = [UIImage imageNamed:#"lock.png"];
}
}
cell.backgroundColor = [UIColor clearColor];
[cell addSubview:squareNameLbl];
[cell addSubview:descLbl];
[cell addSubview:lockImage];
UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 10, 20)];
[image setImage:[UIImage imageNamed:#"arrow_list.png"]];
cell.accessoryView = [[UIImageView alloc]initWithFrame:CGRectMake(260.0, 7.0, 10, 20)];
[cell.accessoryView addSubview:image];
});
// });
//cell.accessoryView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"arrow_list.png"]];
return cell;
}
WebService
#pragma mark - Webservice Methods
-(void)fetchUpcomingSquares
{
NSString *post = [NSString stringWithFormat:#"access_token=%#&page=0",globalAccessToken];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#upcoming_squares",GLOBALURLDOMAIN]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURLResponse *response;
NSError *error =nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"responsedata =%#",responseData);
if(error)
{
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
NSLog(#"HTTP Error: %d %#", httpResponse.statusCode, error);
return;
}
NSLog(#"Error %#", error);
[hud hide:YES];
return;
}
if (responseData == NULL) {
AppDelegate *appdel = [[UIApplication sharedApplication]delegate];
[hud hide:YES];
[appdel alertError];
}
else
{
NSDictionary *parsingResultLogin = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
NSLog(#"parsingResultLogin = %#",parsingResultLogin);
if ([#"-1" isEqualToString:[[parsingResultLogin objectForKey:#"result"]objectForKey:#"error_code"]]) {
NSLog(#"%#",[[parsingResultLogin objectForKey:#"result"]objectForKey:#"error_message"]);
[self showAlertWithMessage:[NSString stringWithFormat:#"%#",[[parsingResultLogin objectForKey:#"result"]objectForKey:#"error_message"]]];
[hud hide:YES];
}
else
{
NSLog(#"Valid ID");
NSDictionary *result= [parsingResultLogin objectForKey:#"result"];
//NSLog(#"result = %#", result);
squareList = [result objectForKey:#"squares"];
NSLog(#"squareList = %#", squareList);
for (NSDictionary *sq in squareList) {
[mySquareArr addObject:[sq objectForKey:#"square_name"]];
[mySquareDescArr addObject:[sq objectForKey:#"max_distance"]];
[accessTypeArr addObject:[sq objectForKey:#"access_type"]];
}
[self.mySquareTblView reloadData];
[hud hide:YES];
}
}
});
NSLog(#"access Type =%#",accessTypeArr);
}

I think it's pretty clear. You're not using your cell identifier on this line of code:
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:nil];
You should do it like this:
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

I used bellow code and it's working fine
[self.tableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:YES];

Related

Data dosen't load on some Tableview cell from JSON parse

I making here simple application on XCODE 7.1. I just display 2 label and 1 image in tableview cell.I am parsing data from this URL. I am simply load data in TableviewHere i put the code of ViewController.m file
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
activityIndicator.alpha = 1.0;
[self.view addSubview:activityIndicator];
activityIndicator.center = CGPointMake([[UIScreen mainScreen]bounds].size.width/2, [[UIScreen mainScreen]bounds].size.height/2);
[activityIndicator startAnimating];//to start animating
// Do any additional setup after loading the view, typically from a nib.
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:#"http://www.androidbegin.com/tutorial/jsonparsetutorial.txt"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
[activityIndicator stopAnimating];
_responsedic = (NSDictionary*) responseObject;
_Worldpopulation = [_responsedic valueForKey:#"worldpopulation"];
_imageURL = [_Worldpopulation valueForKey:#"flag"];
_country = [_Worldpopulation valueForKey:#"country"];
_population = [_Worldpopulation valueForKey:#"population"];
NSLog(#"Data:%#",_imageURL);
NSLog(#"Population",_population);
NSLog(#"Country",_country);
// NSLog(#"%#",_MovieList);
//NSLog(#"Array: %#",_imageURL);
//NSLog(#"%#",responseObject);
}
}];
[dataTask resume];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 10;
}
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *Identifier = #"mycell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:Identifier];
// Set and load the images
[cell.imageView sd_setImageWithURL:[_imageURL objectAtIndex:indexPath.row] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
// Get rid of the activity indicator when the image has been loaded
}];
cell.textLabel.text = [_country objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [_population objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//NSString *rowValue = self.friends[indexPath.row+1];
NSString *message = [[NSString alloc] initWithFormat:#"You selected %#",[_country objectAtIndex:indexPath.row]];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"YOU SELECT"
message:message
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
I am using AFNetworking 3.0 and SDWebImage for image loading.Data parse successfully and and displayed in tableview.I attached screenshot below
Problem is what the all data are not displayed in the tableview cell i also put the Alert dialog on each cell of tableview data successfully loaded but not displayed in cell. I search everywhere i can't find solution for this i am using 3G connection so net speed is not an issue Please someone help.
Try to reload table view with updated data in completion block.
NSURL *URL = [NSURL URLWithString:#"http://www.androidbegin.com/tutorial/jsonparsetutorial.txt"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
[activityIndicator stopAnimating];
_responsedic = (NSDictionary*) responseObject;
_Worldpopulation = [_responsedic valueForKey:#"worldpopulation"];
_imageURL = [_Worldpopulation valueForKey:#"flag"];
_country = [_Worldpopulation valueForKey:#"country"];
_population = [_Worldpopulation valueForKey:#"population"];
NSLog(#"Data:%#",_imageURL);
NSLog(#"Population",_population);
NSLog(#"Country",_country);
// NSLog(#"%#",_MovieList);
//NSLog(#"Array: %#",_imageURL);
//NSLog(#"%#",responseObject);
//Added Code -> Reloading data on Main queue for update
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableview reloadData];
});
}
}];
[dataTask resume];
Hope, it'll help you.
Thanks.
1) Parse Data and after getting data relaod table
-(void)ParseData
{
NSURLSession * session = [NSURLSession sharedSession];
NSURL * url = [NSURL URLWithString: #"http://www.androidbegin.com/tutorial/jsonparsetutorial.txt"];
//Create URLReques
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
// Set Method POST/GET
[request setHTTPMethod:#"GET"];
// Asynchronously Api is hit here
NSURLSessionDataTask* dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (!error) //If error nil
{
//Serialization data
NSDictionary * json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"json %#",json);
array=[json valueForKey:#"worldpopulation"];
dispatch_async(dispatch_get_main_queue(), ^(void) {
if(array.count!=0)
{
//Reload table View
[_tblView reloadData];
}
});
}
else
{
//failure;
}
}];
[dataTask resume] ; // Executed task
}
2) Table View DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(array.count!=0)
{
return [array count];
}
return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell;
//= [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell.backgroundColor =[UIColor whiteColor];
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
UILabel *lblCountry=(UILabel*)[cell viewWithTag:2];
lblCountry.text= [[array objectAtIndex:indexPath.row]valueForKey:#"country"];
UILabel *lblPopulation=(UILabel*)[cell viewWithTag:3];
lblPopulation.text= [[array objectAtIndex:indexPath.row]valueForKey:#"population"];
UIImageView *img = (UIImageView *)[cell viewWithTag:1];
[img setImageWithURL:[NSURL URLWithString:[[array objectAtIndex:indexPath.row]valueForKey:#"flag"]]];
return cell;
}

How to populate UITableView with JSON data?

I'm struggling to figure out what i am doing wrong. I am basically trying to populate the my UITableView with json data. In the console I can see the results but just don't know why the data is not displayed in the tableview. I have looked at similar questions and answers but none is a solution to my problem.
Advice or help please;
#pragma mark - Private method implementation
-(void)loadData{
// Form the query.
#try {
NSString *get =[[NSString alloc] initWithFormat:#""];
NSString *getRegions = [NSString stringWithFormat:#"JSON URL HERE",self.sessionId, self.companyId];
NSURL *url=[NSURL URLWithString:getRegions];
NSLog(#"Get regions: %#", url);
NSData *postData = [get dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:postData];
//[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Reponse code: %ld", (long)[response statusCode]);
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#", responseData);
#try{
NSError *error = nil;
regionsJson = [[NSMutableArray alloc]init];
//[jsonData removeAllObjects];
regionsJson = [NSJSONSerialization JSONObjectWithData:urlData options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&error];
NSArray *tblArray = [NSArray arrayWithObject:regionsJson];
}
#catch (NSException *e){
NSLog(#"Try catch block: %#", e);
}
#finally{
// [self.tblRegion reloadData];
NSLog(#"finally");
}
structureJson =[regionsJson valueForKey:#"structure"];
companyJson =[structureJson valueForKey:#"company"];
_barBtnCompanyName.title = [companyJson valueForKey:#"company_name"];
NSLog(#"Get company name: %#", [companyJson valueForKey:#"company_name"]);
for (int i =0 ; i < regionsJson.count; i++){
regionsJson = [companyJson objectForKey:#"regions"];
NSString *regionName = [NSString stringWithFormat:#"%#", [regionsJson valueForKey:#"region_name"]];
NSLog(#"Region name: %#",regionName);
// [regionsJson addObject:regionName];
NSString *alarmCount = [NSString stringWithFormat:#"%#", [regionsJson valueForKey:#"alarm_cnt"]];
NSLog(#"Alarm count: %#", alarmCount);
// [regionsJson addObject:alarmCount];
}
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
}
// Reload the table view.
[self.tblRegion reloadData];
}
#pragma mark - UITableView method implementation
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSLog(#"Number of rows: %lu", (unsigned long)regionsJson.count);
return [regionsJson count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"CellRegions";
// Dequeue the cell.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// Set the loaded data to the appropriate cell labels.
cell.textLabel.text = [[regionsJson objectAtIndex:indexPath.row] objectForKey:#"region_name"];
cell.detailTextLabel.text = [[regionsJson objectAtIndex:indexPath.row] objectForKey:#"alarm_cnt"];
[cell setAccessoryType: UITableViewCellAccessoryDisclosureIndicator];
NSLog(#"Table cell: %#", cell);
return cell;
}
My code is just fine, i did a stupid omission of this declaration.
-(void)viewDidLoad{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.tblRegion.delegate = self;
self.tblRegion.dataSource = self;
[self loadData];
}

how to reload table view when I'm in a class?

I have a table view on InquiryViewController that I want to be reloaded when I click the update status button. The update status button is a JSON that gets the status of a message.
Here's the code:
-(BOOL)getMessageStatus : (NSMutableArray *)emails : (UIAlertView *)alert : (UIProgressView *)progress : (InquiryLogViewController *)controller
{
_emailsInApi = [[NSArray alloc]init];
_emailsInApi = [[DBManager getSharedInstance]arrayOfEmails];
NSMutableArray *newArrayEmail = [[NSMutableArray alloc]init];
NSString *arrayEmail =#"";
for(int i = 0; i<[_emailsInApi count]; i++){
arrayEmail = [_emailsInApi objectAtIndex:i];
[newArrayEmail addObject:arrayEmail];
}
NSURL *url = [NSURL URLWithString:#"http://www.url.com/API/2.0/message.php"];
NSDictionary *params =#{#"api_key":#"APIKEYIOS",#"action":#"get-message-status",#"email":newArrayEmail};
NSLog(#"params: %#",params);
NSData *paramsData = [NSJSONSerialization dataWithJSONObject:params
options:NSJSONWritingPrettyPrinted
error:nil];
NSString *paramsString = [[NSString alloc]initWithData:paramsData encoding:NSUTF8StringEncoding];
paramsString = [paramsString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
paramsString = [paramsString stringByReplacingOccurrencesOfString:#"%5C" withString:#""];
NSString *post = [NSString stringWithFormat:#"params=%#", paramsString];
NSData *sendData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:sendData];
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
if (!error)
{
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"response...... = %#", responseString );
//get data frm response
self.responseData = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
self.responseArray = [self.responseData objectForKey:#"data"];
for(NSDictionary *items in self.responseArray)
{
Inquiry *inq = [[Inquiry alloc]init];
inq.email = [items objectForKey:#"to_email"];
inq.status = [items objectForKey:#"status_id"];
[emails addObject:inq];
}
float newProg = (float)1 - (float)[emails count] / (float)5;
dispatch_async(dispatch_get_main_queue(), ^{
[progress setProgress:newProg animated:YES];
});
dispatch_async(dispatch_get_main_queue(), ^{
[[DBManager getSharedInstance]updateInquirylog:emails];
});
dispatch_async(dispatch_get_main_queue(), ^{
controller.arrayOfEmails = [[DBManager getSharedInstance]loadInquiries];
[controller.tableViews reloadData];
});
dispatch_async(dispatch_get_main_queue(), ^{
[alert dismissWithClickedButtonIndex:0 animated:YES];
});
}
else
{
self.alert = [[UIAlertView alloc] initWithTitle:nil message:error.localizedDescription delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
self.responseData = nil;
[alert show];
}
}];
[task resume];
return YES;
}
My problem here is in: [controller.tableViews reloadData];
It doesn't reload my table. Why? Help me please. Thank you
EDIT: This json is in a class
Ok I'm sorry. I forgot to include my table view method.
Here it is:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID =#"Cell";
tableCellOfInquiryLog *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (tableView == self.searchDisplayController.searchResultsTableView){
if(cell == nil)
{
NSArray *topLevelObjects = [[NSBundle mainBundle]loadNibNamed:#"searchCell" owner:self options:nil];
cell = [topLevelObjects objectAtIndex:0];
}
Inquiry *inquiry = [searchResult objectAtIndex:indexPath.row];
cell.sInquiry_id.text =[NSString stringWithFormat:#"%d",inquiry.ID];
cell.sName.text = inquiry.name;
cell.sItem.text = inquiry.item_name;
cell.sDate.text = inquiry.dDate;
cell.status.layer.cornerRadius = 10;
if ([inquiry.status isEqual: #"1"]) {
cell.status.backgroundColor = [UIColor greenColor];
}
else if ([inquiry.status isEqual: #"2"]) {
cell.status.backgroundColor = [UIColor orangeColor];
}
else if ([inquiry.status isEqual: #"3"]) {
cell.status.backgroundColor = [UIColor redColor];
}
return cell;
}
else
{
if(cell == nil)
{
cell = [[tableCellOfInquiryLog alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
}
Inquiry *inquiry = [arrayOfInquiries objectAtIndex:indexPath.row];
cell.inquiry_id.text =[NSString stringWithFormat:#"%d",inquiry.ID];
cell.name.text = inquiry.name;
cell.item.text = inquiry.item_name;
cell.date.text = inquiry.dDate;
cell.status.layer.cornerRadius = 10;
if ([inquiry.status isEqual: #"1"]) {
cell.status.backgroundColor = [UIColor greenColor];
}
else if ([inquiry.status isEqual: #"2"]) {
cell.status.backgroundColor = [UIColor orangeColor];
}
else if ([inquiry.status isEqual: #"3"]) {
cell.status.backgroundColor = [UIColor redColor];
}
return cell;
}
return nil;
}
create a instance of your tableview and the add the given code in which ever method u want to add to [self.nameoftableview reloaddata]
if (indexPath.section ==1) {
cell = [tableView dequeueReusableCellWithIdentifier:section1identifier];
cell = nil;//here i have made it nil
if (!cell)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:section1identifier];
data *newObj = [callingObj.itemslist objectAtIndex:indexPath.row];
UITextView *titlelabel = [[UITextView alloc]initWithFrame:CGRectMake(cell.frame.origin.x+5, cell.frame.origin.y-2, 320, 38)];
titlelabel.textColor = [UIColor redColor];
titlelabel.font= [UIFont fontWithName:#"Times New Roman" size:FONT_SIZE];
titlelabel.text = newObj.title;
titlelabel.scrollEnabled = NO;
titlelabel.editable = NO;
[cell.contentView addSubview:titlelabel];
desView = [[UITextView alloc]initWithFrame:CGRectMake(cell.frame.origin.x,cell.frame.origin.y+25 , 320, i + 160)];
desView.text = newObj.description;
desView.editable = NO;
desView.hidden = NO;
[cell.contentView addSubview:desView];
if (check == NO) {
desView.hidden = YES;
}
}
}
return cell;

How can I add load more in UITableView [duplicate]

This question already has answers here:
How to implement "Load 25 More" in UITableViewController
(4 answers)
Closed 9 years ago.
Can you help me about load more UITableView? I use load more methods, but all records returns instead of 25.What is wrong in code? please help :S Thanks for replying
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad{
itemArray = [[NSMutableArray alloc] init];
[self ServiseBaglan];}
- (void)ServiseBaglan{
NSString *soapMessage = [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<SOAP-ENV:Envelope \n"
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" \n"
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n"
"xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\"\n"
"SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" \n"
"xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"> \n"
"<SOAP-ENV:Body> \n"
"<OnemliYer xmlns=\"http://tempuri.org/\">\n"
"<station>%#</station>\n"
"<dilId>%#</dilId>\n"
"</OnemliYer> \n"
"</SOAP-ENV:Body> \n"
"</SOAP-ENV:Envelope>\n", izmir , #"1"];
NSURL *url = [NSURL URLWithString:#"http://www.manavgatportal.com/Service1.svc"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"http://tempuri.org/IService1/OnemliYer" forHTTPHeaderField:#"Soapaction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
// NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
NSURLConnection *theConnection = [[NSURLConnection alloc]initWithRequest:theRequest delegate:self];
if(theConnection) {
// webData = [[NSMutableData data] retain];
webData = [[NSMutableData data]init];
}
else {
NSLog(#"theConnection is NULL");
}
[self.tableView reloadData];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath
*)indexPath{
return 40;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section
{
if ([itemArray count] >= 25) {
count= [itemArray count] + 1;
NSLog(#": %d", count);
}else
{
count=[itemArray count];
NSLog(#": %d", count);
}
return count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
static NSString *CellIdentifier2 = #"Cell2";
static NSInteger TitleTag = 2;
static NSInteger AddresseTag = 1;
UITableViewCell *cell;
if (indexPath.row != [itemArray count] ) {
cell= (UITableViewCell *) [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier];
}
NSDictionary *Item = [itemArray objectAtIndex:indexPath.row];
UIFont *font = [UIFont fontWithName:#"Arial" size:14];
cell.textLabel.font = font;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.detailTextLabel.numberOfLines = 2;
cell.textLabel.text = [Item objectForKey:#"a:Ad"];
cell.detailTextLabel.text = [Item objectForKey:#"a:Ilce"];
[[cell textLabel] setBackgroundColor:[UIColor clearColor]];
[[cell detailTextLabel] setBackgroundColor:[UIColor clearColor]];
}
else {
if(indexPath.row == count-1)
{
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2];
}
UILabel *loadMore =[[UILabel alloc]initWithFrame: CGRectMake(0,0,320,30)];
loadMore.textColor = [UIColor blackColor];
loadMore.highlightedTextColor = [UIColor darkGrayColor];
loadMore.backgroundColor = [UIColor clearColor];
loadMore.font=[UIFont fontWithName:#"Verdana" size:14];
loadMore.textAlignment=UITextAlignmentCenter;
loadMore.font=[UIFont boldSystemFontOfSize:14];
loadMore.text=#"load More...";
[cell addSubview:loadMore];
}
}
return cell;
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
[self.tableView reloadData];
}
I do not think it is good design to redefine your count variable in numberOfRowsInSection.
Rather, you should do this where you actually change the itemsArray. A good place is during the initialisation of the view, and after pressing "load 25 more".
Also, you could consider eliminating the variable altogether and using itemArray.count+1 instead.

App Crashes when ReloadData done for the tableView

I am using the following code to reload my tableView when its done adding all the data to my Mutable Arrays, but the app always crashes
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
//Spinner Add while waiting
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
spinner.frame = CGRectMake(147, 10, 25, 25);
[self.tableView addSubview:spinner];
[spinner startAnimating];
operationQueue = [[NSOperationQueue alloc] init];
usersFirstName = [[NSMutableArray alloc] init];
usersLastName = [[NSMutableArray alloc] init];
usersAvatar = [[NSMutableArray alloc] init];
NSString *urlstring = [NSString stringWithFormat:#"https://www.test.com/scribble/%#/",scribbleId];
NSURL *url = [NSURL URLWithString:urlstring];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON){
users = JSON[#"users_favored"];
if (users.count > 0) {
NSUInteger count = [users count];
for (NSUInteger i =0; i<count; i++) {
NSString *urlString = [NSString stringWithFormat:#"https://www.test.com%#",[users objectAtIndex:i]];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *requestUser = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:requestUser success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON){
if (i == 0) {
usersFirstName = [JSON[#"first_name"] mutableCopy];
usersLastName = [JSON[#"last_name"] mutableCopy];
usersAvatar = [JSON[#"user_avatar"] mutableCopy];
}else{
[usersFirstName addObjectsFromArray:JSON[#"first_name"]];
[usersLastName addObjectsFromArray:JSON[#"last_name"]];
[usersAvatar addObjectsFromArray:JSON[#"user_avatar"]];
}
if (i == count-1) {
[self.tableView reloadData];
[spinner stopAnimating];
[spinner removeFromSuperview];
}
}failure:nil];
[operationQueue addOperation:operation];
}
}else{
self.navigationItem.title = #"No Favors";
[spinner stopAnimating];
[spinner removeFromSuperview];
}
} failure:nil];
[operationQueue addOperation:operation];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return usersFirstName.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableFavorIdentifier = #"FavorCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableFavorIdentifier];
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableFavorIdentifier];
}
NSString *firstName = [usersFirstName objectAtIndex:indexPath.row];
NSString *lastName = [usersLastName objectAtIndex:indexPath.row];
NSString *avatar = [usersAvatar objectAtIndex:indexPath.row];
NSString *userFullName = [NSString stringWithFormat:#"%# %#",firstName,lastName];
UIImageView *userAvatar = (UIImageView *)[cell viewWithTag:100];
if ([avatar length ] > 0) {
NSString *img = [#"https://dtest_media_and_assets.s3.amazonaws.com/" stringByAppendingString:avatar];
[userAvatar setImageWithURL:[NSURL URLWithString:img] placeholderImage:[UIImage imageNamed:#"scribble.png"]];
}else{
userAvatar.image = [UIImage imageNamed:#"scribble.png"];
}
userAvatar.layer.cornerRadius = 4.0;
userAvatar.clipsToBounds = YES;
UILabel *userNameLabel = (UILabel *)[cell viewWithTag:101];
userNameLabel.text = userFullName;
return cell;
}
The error it gives is
2013-03-15 16:37:08.910 test[19547:c07] -[__NSCFString count]: unrecognized selector sent to instance 0x8679c80
2013-03-15 16:37:08.911 test[19547:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString count]: unrecognized selector sent to instance 0x8679c80'
*** First throw call stack:
(0x1cdf012 0x169fe7e 0x1d6a4bd 0x1ccebbc 0x1cce94e 0x143d7 0x7c8548 0x7cb224 0x68f952 0x68f2dc 0x140d7 0x281d2 0x29569 0x2f9553f 0x2fa7014 0x2f977d5 0x1c85af5 0x1c84f44 0x1c84e1b 0x21bb7e3 0x21bb668 0x5e3ffc 0x200d 0x1f35)
libc++abi.dylib: terminate called throwing an exception
Edit
everything works just fine when I use this instead
[usersFirstName addObject:JSON[#"first_name"]];
[usersLastName addObject:JSON[#"last_name"]];
[usersAvatar addObject:JSON[#"user_avatar"]];
[self.tableView reloadData];
if (i == count-1) {
[spinner stopAnimating];
[spinner removeFromSuperview];
}
try the same with that function:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"usersFirstName is of type %#", NSStringFromClass([usersFirstName class]));
return [usersFirstName count];
}
I guess you have to replace:
if (i == 0) {
usersFirstName = [JSON[#"first_name"] mutableCopy];
usersLastName = [JSON[#"last_name"] mutableCopy];
usersAvatar = [JSON[#"user_avatar"] mutableCopy];
}else{
[usersFirstName addObjectsFromArray:JSON[#"first_name"]];
[usersLastName addObjectsFromArray:JSON[#"last_name"]];
[usersAvatar addObjectsFromArray:JSON[#"user_avatar"]];
}
with just:
[usersFirstName addObject:JSON[#"first_name"]];
[usersLastName addObject:JSON[#"last_name"]];
[usersAvatar addObject:JSON[#"user_avatar"]];
The issue is that this:
users = JSON[#"users_favored"];
Returns an NSString, when it looks you are expecting an NSArray.
Verify this using:
users = JSON[#"users_favored"];
NSLog(#"users is of type %#", NSStringFromClass([users class]));
Something is either wrong with your assumption or the JSON is broken.

Resources