iOS: why second section is not displayed in UITableView? - ios

My .h file :
#interface ViewPrescriptionViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>
#property(weak, nonatomic) NSArray *arr;
#property (nonatomic, retain) NSArray *menuItems;
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#property (nonatomic, retain) NSArray *medicineItems;
#end
My .m file :
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
/* Here i send parameter to server using AFNetworking, and i got response from server ,
menu_itemes: (
{
bp = "000/000";
dateTime = "05/12/2016 01:02:59 PM";
doc = {
"email_id" = "batra#gmail.com";
exception = 0;
gender = Male;
id = 0;
"mobile_no" = 1234567890;
name = Batra;
"profile_id" = 0;
qualification = "MD(Doctor)";
"reg_id" = 157;
salutation = Mr;
"wellness_id" = 251215782521;
};
"follow_up" = 17;
id = 37;
medicine = (
"Syrup,Decold Total,20,0-0-1,Before Meal,1",
"Injection,Insulin,1,0-0-1,Before Meal,1",
no,
no,
no,
no,
no,
no,
no,
no
);
patient = {
"email_id" = "bishtrohit#gmail.com";
exception = 0;
gender = Male;
id = 0;
"mobile_no" = 1234567890;
name = Rohit;
"profile_id" = 0;
qualification = "";
"reg_id" = 150;
salutation = Mr;
"wellness_id" = 290119935030;
};
weight = 000;
}
)
*/
[manager POST:Loginurl parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"Response from view Prescription server : %#", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
// menuItems=#[#"%#",[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]];
NSArray *ResponseArray = [NSJSONSerialization JSONObjectWithData: responseObject options: kNilOptions error: nil];
if (ResponseArray.count >0)
{
self.menuItems = [[NSMutableArray alloc]initWithArray:ResponseArray];
[_tableView reloadData];
//menuItems = [ResponseArray mutableCopy];
NSLog(#"menu_itemes: %#",self.menuItems);
}
NSMutableArray *Myarray = [NSMutableArray new];
for (int i=0; i<_menuItems.count; i++) {
[Myarray addObject:[[_menuItems objectAtIndex:i] objectForKey:#"medicine"]];
NSLog(#"medicine: %#",Myarray);
}
if (Myarray.count>0) {
self.medicineItems=[NSArray arrayWithArray:Myarray];
//[_tableView reloadData];
NSLog(#"medicine items : %#",self.medicineItems);
NSLog(#"medicine items count : %lu",(unsigned long)self.medicineItems.count);
}
// _arr=[NSArray arrayWithArray:ResponseArray];
// NSLog(#"menu_itemes: %#",_menuItems);
[self getdata:responseObject];
} failure:^(NSURLSessionTask *operation, NSError *error)
{
......
Then
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (section == 0)
{
return 1;
}
else
{
NSLog(#"S");
//here is breakpoint
return self.medicineItems.count;
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 0)
{
NSDictionary *content = [self.menuItems objectAtIndex:indexPath.row];
NSLog(#"content = %#",content);
ViewPrescriptionTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:#"PatientDetail" forIndexPath:indexPath];
[cell.datetime setText:[content valueForKey:#"dateTime"]];
[cell.bp setText:[content valueForKey:#"bp"]];
[cell.weight setText:[content valueForKey:#"weight"]];
[cell.followup setText:[content valueForKey:#"follow_up"]];
[cell.doctorname setText:[[content objectForKey:#"doc"]valueForKey:#"name"]];
[cell.mobile setText:[NSString stringWithFormat:#"%#",[[content objectForKey:#"doc"]valueForKey:#"mobile_no"]]];
[cell.email setText:[[content objectForKey:#"doc"]valueForKey:#"email_id"]];
[cell.qualification setText:[[content objectForKey:#"doc"]valueForKey:#"qualification"]];
[cell.wellnessid setText:[[content objectForKey:#"doc"]valueForKey:#"wellness_id"]];
[cell.patientname setText:[[content objectForKey:#"patient"]valueForKey:#"name"]];
[cell.patientmobile setText:[NSString stringWithFormat:#"%#",[[content objectForKey:#"patient"]valueForKey:#"mobile_no"]]];
[cell.patientemail setText:[[content objectForKey:#"patient"]valueForKey:#"email_id"]];
[cell.patientwellnessid setText:[[content objectForKey:#"patient"]valueForKey:#"wellness_id"]];
return cell;
}
else{
//Cell For Medicines
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:#"PatientDetail" forIndexPath:indexPath];
NSLog(#"s");
//here is breakpoint
[cell.textLabel setText:[self.medicineItems objectAtIndex:indexPath.row]];
return cell;
}
}
In Storyboard
I have taken UITableView on screen for this.
I have taken 1 static custom cell for this.
What i want :
I want two section, in first, i displayed all data which i receive from server except medicinItems like following image:
In second section,
I want to pass medicinItems in that.
but my problem is, second section is not displaped.
But i don't know how to do that..??
Please anyone can solve my issue. help will be appreciable.

You need to reload data after fetching from server and updating medicineItems:
if (Myarray.count>0) {
self.medicineItems=[NSArray arrayWithArray:Myarray];
dispatch_async(dispatch_get_main_queue(), ^{
[_tableView reloadData];
});
}
Furthermore:
[cell.textLabel setText:[self.medicineItems objectAtIndex:indexPath.row]];
self.medicineItems is not an array of strings in this case so you can't set the textLabel to that object

Related

Json issue in tableview with stepper and lable

I am new in ios developer.
I want to selected data into other tableview my problem is i dont know how to get the name and quantity.
See here is my screen shot
My json data like this format
{
Data = (
{
"Dry_cleaning" = 49;
Iron = 8;
Name = "Shirt/Tees";
Wash = 15;
"Wash_Iron" = 19;
id = 1;
},
{
"Dry_cleaning" = 49;
Iron = 5;
Name = "Kurta(short)";
Wash = 20;
"Wash_Iron" = 19;
id = 2;
},
{
"Dry_cleaning" = 50;
Iron = 8;
Name = "Kurta(Long)";
Wash = 15;
"Wash_Iron" = 20;
id = 3;
},
{
"Dry_cleaning" = 50;
Iron = 5;
Name = Shorts;
Wash = 15;
"Wash_Iron" = 19;
id = 4;
},
{
"Dry_cleaning" = 55;
Iron = 8;
Name = "Trousers/Pyjamas";
Wash = 20;
"Wash_Iron" = 30;
id = 5;
},
{
"Dry_cleaning" = 70;
Iron = 7;
Name = Jeans;
Wash = 20;
"Wash_Iron" = 29;
id = 6;
},
{
"Dry_cleaning" = 150;
Iron = 5;
Name = Blazer;
Wash = 25;
"Wash_Iron" = 19;
id = 7;
},
{
"Dry_cleaning" = 100;
Iron = 6;
Name = "Leather_Jacket";
Wash = 30;
"Wash_Iron" = 36;
id = 8;
}
}
Here this is my code
ViewController.h
import
#interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
#property (weak, nonatomic) IBOutlet UITableView *tableview;
#property (strong, nonatomic)NSMutableArray *arrayCounts;
- (IBAction)placeorder:(id)sender;
#end
ViewController.m
//
// ViewController.m
// orderscreenfile
//
// Created by Tranetech on 02/02/16.
// Copyright (c) 2016 Tranetech. All rights reserved.
//
#import "ViewController.h"
#import "custom.h"
#interface ViewController ()
{
NSDictionary *dic_property;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[NSThread detachNewThreadSelector:#selector(fetchdata) toTarget:self withObject:nil];
//[NSThread detachNewThreadSelector:#selector(arrycount) toTarget:self withObject:nil];
self.arrayCounts = [NSMutableArray array];
NSLog(#"array count=%d",self.arrayCounts.count);
[self.tableview reloadData];
// Do any additional setup after loading the view, typically from a nib.
}
//-(void)arrycount
//{
// for (int i = 0; i<[[dic_property objectForKey:#"Data"] count]; i++) {
// [self.arrayCounts insertObject:[NSString stringWithFormat:#"0"] atIndex:i];
// }
//
//}
-(void)fetchdata
{
NSString *login= [[NSString stringWithFormat:#"http://men_dry.php"]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"----%#", login);
NSURL *url = [NSURL URLWithString:[login stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//-- Get request and response though URL
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (data) {
dic_property= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(#"%#", dic_property);
NSLog(#"counts=%d",[[dic_property objectForKey:#"Data"]count]);
for (int i = 0; i<[[dic_property objectForKey:#"Data"] count]; i++) {
[self.arrayCounts insertObject:[NSString stringWithFormat:#"0"] atIndex:i];
}
[self.tableview reloadData];
}
else {
NSLog(#"network error, %#", [error localizedFailureReason]);
}
});
}];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.arrayCounts.count;
// return [[dic_property objectForKey:#"Data"]count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
custom *cell;
static NSString *simpleTableIdentifier = #"customcell";
cell = (custom *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
cell = [[[NSBundle mainBundle] loadNibNamed:#"customcell" owner:self options:nil] objectAtIndex:0];
cell.lblcount.text = self.arrayCounts[indexPath.row];
cell.lbltitle.text=[[[dic_property objectForKey:#"Data"]objectAtIndex:indexPath.row]objectForKey:#"Name"];
cell.lblcount.tag=indexPath.row;
[cell.stepper addTarget:self action:#selector(itemsChange:) forControlEvents:UIControlEventValueChanged];
return cell;
}
- (void)itemsChange:(UIStepper*)stepper
{
CGPoint cursorPosition = [stepper convertPoint:CGPointZero toView:self.tableview];
NSIndexPath *indexPath = [self.tableview indexPathForRowAtPoint:cursorPosition];
custom *currentCell = (custom *)[self.tableview cellForRowAtIndexPath:indexPath];
currentCell.lblcount.text=[NSString stringWithFormat:#"%f",[stepper value]];
[self.arrayCounts replaceObjectAtIndex:indexPath.row withObject:[NSString stringWithFormat:#"%f",[stepper value]]];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)placeorder:(id)sender {
}
#end
I am stuck into three days please solve my problem
Thanks in ADVANCE.
#Arpit replace your code with Arry.
viewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
#property (weak, nonatomic) IBOutlet UITableView *tableview;
#property (strong, nonatomic)NSMutableArray *arrayCounts;
- (IBAction)placeorder:(id)sender;
#property (weak, nonatomic) IBOutlet UIButton *placeorder;
#end
ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
[NSThread detachNewThreadSelector:#selector(fetchdata) toTarget:self withObject:nil];
self.arrayCounts = [NSMutableArray array];
NSLog(#"array count=%lu",(unsigned long)self.arrayCounts.count);
}
-(void)fetchdata
{
NSArray *tempArray = #[#{#"Dry_cleaning" : #"49",
#"Iron":#"5",
#"Name":#"Shirt/Tees",
#"Wash":#"20",
#"Wash_Iron":#"19",
#"id":#"1"},
#{#"Dry_cleaning" : #"49",
#"Iron":#"5",
#"Name":#"Kurta(short)",
#"Wash":#"20",
#"Wash_Iron":#"19",
#"id":#"2"},
#{#"Dry_cleaning" : #"49",
#"Iron":#"5",
#"Name":#"Kurta(Long)",
#"Wash":#"15",
#"Wash_Iron":#"20",
#"id":#"3"},
#{#"Dry_cleaning" : #"50",
#"Iron":#"5",
#"Name":#"Shorts",
#"Wash":#"15",
#"Wash_Iron":#"19",
#"id":#"4"},
#{#"Dry_cleaning" : #"51",
#"Iron":#"5",
#"Name":#"Trousers/Pyjamas",
#"Wash":#"20",
#"Wash_Iron":#"19",
#"id":#"5"}];
// remove comment from below code and add where responce will come. -----------------
// NSArray *tempArray = dic_property[#"Data"];
[tempArray enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSMutableDictionary *dictValues = [NSMutableDictionary dictionaryWithDictionary:obj];
[dictValues setValue:#"0" forKey:#"counts"];
[self.arrayCounts addObject:dictValues];
}];
[self.tableview reloadData];
//--------------------------------
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.arrayCounts.count;
// return [[dic_property objectForKey:#"Data"]count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
custom *cell;
static NSString *simpleTableIdentifier = #"customcell";
cell = (custom *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
cell = [[[NSBundle mainBundle] loadNibNamed:#"custom" owner:self options:nil] objectAtIndex:0];
cell.lblCount.text = self.arrayCounts[indexPath.row][#"counts"];
cell.lbltitle.text=self.arrayCounts[indexPath.row][#"Name"];;
[cell.stepper addTarget:self action:#selector(itemsChange:) forControlEvents:UIControlEventValueChanged];
return cell;
}
- (void)itemsChange:(UIStepper*)stepper
{
CGPoint cursorPosition = [stepper convertPoint:CGPointZero toView:self.tableview];
NSIndexPath *indexPath = [self.tableview indexPathForRowAtPoint:cursorPosition];
custom *currentCell = (custom *)[self.tableview cellForRowAtIndexPath:indexPath];
double value = [stepper value];
[currentCell.lblCount setText:[NSString stringWithFormat:#"%d", (int)value]];
self.arrayCounts[indexPath.row][#"counts"] = [NSString stringWithFormat:#"%d",(int)value];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
- (IBAction)placeorder:(id)sender {
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"counts != %#",#"0"];
NSArray *filteredArray = [self.arrayCounts filteredArrayUsingPredicate:predicate];
NSLog(#"yoyr arry:%#",filteredArray);
}
You are following the wrong way to do this. Just use an array which have initial value 0 on all index and set array value to label in cellForRowAtIndexPath than update the array index value on click on stepper event than reload your table with updated array.

Parsing YouTube JSON

I'm having trouble parsing JSON from YouTube. I'm trying to get the title, videoId, and default thumbnail URL. I've parsed JSON before but I'm having issues getting what I want from this.
Here is my code. It's crashing with an unrecognized selector error on NSDictionary* snippet = [item objectForKey:#"snippet"]; The error is -[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x108781b0
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#define storeURL [NSURL URLWithString: #"https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=25&playlistId=UUkfYL7q5G8CYtZgtSAwmwzw&key=AIzaSyBS4do208_KPGHAhszfVkHadSvtfSgr7Mo"]
#import "KFBYoutubeVideosTableViewController.h"
#import "SVProgressHUD.h"
#import "Reachability.h"
#import "TSMessage.h"
#import "TSMessageView.h"
#interface KFBYoutubeVideosTableViewController ()
#end
#implementation KFBYoutubeVideosTableViewController
#synthesize title, videoID, thumbURL, url, titleArray, videoIDArray, thumbArray;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[[SVProgressHUD appearance]setHudBackgroundColor:[UIColor blackColor]];
[[SVProgressHUD appearance]setHudForegroundColor:[UIColor whiteColor]];
[SVProgressHUD showWithStatus:#"Loading"];
Reachability *networkReachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
if(networkStatus == NotReachable)
{
[TSMessage showNotificationWithTitle:#"Network Error" subtitle:#"No active network connection!" type:TSMessageNotificationTypeError];
[SVProgressHUD dismiss];
}
self.title = #"KFB Videos";
self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
self.tableView.backgroundColor = [UIColor darkGrayColor];
url = [NSURL URLWithString:#"https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=25&playlistId=UUkfYL7q5G8CYtZgtSAwmwzw&key=AIzaSyBS4do208_KPGHAhszfVkHadSvtfSgr7Mo"];
dispatch_async(kBgQueue, ^{
NSData *data = [NSData dataWithContentsOfURL:url];
if (data == nil)
{
NSLog(#"data is nil");
}
else
{
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
}
});
}
- (void)viewDidDisappear:(BOOL)animated
{
[SVProgressHUD dismiss];
}
- (void)fetchedData:(NSData *)responseData
{
NSError *error;
titleArray = [[NSMutableArray alloc]init];
videoIDArray = [[NSMutableArray alloc]init];
thumbArray = [[NSMutableArray alloc]init];
NSArray *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"%#", json);
for (NSDictionary *item in json)
{
NSDictionary* snippet = [item objectForKey:#"snippet"];
title = [snippet objectForKey:#"title"];
videoID = [[snippet objectForKey:#"resourceId"] objectForKey:#"videoID"];
thumbURL = [[[snippet objectForKey:#"thumbnails"] objectForKey:#"default"] objectForKey:#"url"];
[titleArray addObject:title];
[videoIDArray addObject:videoID];
[thumbArray addObject:thumbURL];
}
[self.tableView reloadData];
[SVProgressHUD dismiss];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [titleArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"Cell"];
cell.textLabel.font = [UIFont systemFontOfSize:16.0];
}
if (cell)
{
cell.backgroundColor = [UIColor clearColor];
cell.textLabel.text = [titleArray objectAtIndex:indexPath.row];
cell.textLabel.textColor = [UIColor blackColor];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"Title: %#, Video ID: %#, Thumbnail URL: %#", [titleArray objectAtIndex:indexPath.row],[videoIDArray objectAtIndex:indexPath.row], [thumbArray objectAtIndex:indexPath.row]);
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Here is the JSON:
{
etag = "\"bvxF-DWHx1toJotsdJBeCm43SLs/tyIRY5zDT7R6YEirBFeFh0tVLCw\"";
items = (
{
etag = "\"bvxF-DWHx1toJotsdJBeCm43SLs/ON_wGC8nyy0H_bqRqQHlA7mXiM0\"";
id = UUstIg9nSlWxTaKpWq7G0sppJf9oH5NaDE;
kind = "youtube#playlistItem";
snippet = {
channelId = UCkfYL7q5G8CYtZgtSAwmwzw;
channelTitle = "Kentucky Farm Bureau";
description = "Celebrate June as National Dairy Month with a visit to Jericho Acres Dairy Farm in Henry County.";
playlistId = UUkfYL7q5G8CYtZgtSAwmwzw;
position = 0;
publishedAt = "2014-05-22T12:28:03.000Z";
resourceId = {
kind = "youtube#video";
videoId = VSCr40jERks;
};
thumbnails = {
default = {
height = 90;
url = "https://i1.ytimg.com/vi/VSCr40jERks/default.jpg";
width = 120;
};
high = {
height = 360;
url = "https://i1.ytimg.com/vi/VSCr40jERks/hqdefault.jpg";
width = 480;
};
maxres = {
height = 720;
url = "https://i1.ytimg.com/vi/VSCr40jERks/maxresdefault.jpg";
width = 1280;
};
medium = {
height = 180;
url = "https://i1.ytimg.com/vi/VSCr40jERks/mqdefault.jpg";
width = 320;
};
standard = {
height = 480;
url = "https://i1.ytimg.com/vi/VSCr40jERks/sddefault.jpg";
width = 640;
};
};
title = "Kentucky Farm Bureau Reports June 2014";
};
},
If you look closely title is not at bottom of the json response. Everyone of those nodes is a dictionary. So to get the things you want from your code you have to do this :
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSArray *items = [json objectForKey:#"items"];
for (NSDictionary *item in json)
{
NSDictionary* snippet = [item objectForKey:#"snippet"];
title = [snippet objectForKey:#"title"];
videoID = [[snippet objectForKey:#"resourceId"] objectForKey:#"videoId"];
thumbURL = [[[snippet objectForKey:#"thumbnails"] objectForKey:#"default"] objectForKey:#"url"];
}
If you are planning to do more stuff with this data i recommend you create objects and parse the json when creating each object. so you can keep track of other properties in future. It is much cleaner then this way.

tableview crash with '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'

I got a problem.
I have a TableView in my ViewController. This TableView has 5 rows with textFields. The height of each row is 156 pixels. also I have button "Save", and after click I want save all my data to NSMutableArray in following method, but in result I got an error.
What should I do in this way?
thank you
my method example:
- (void) saveDataToArray
{
carCellTableViewCell * cell;
_carNewPrices = [[NSMutableArray alloc] init];
for (int i = 0; i < 5; i++)
{
cell = (carCellTableViewCell *)[_meTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
[_carPrices addObject:cell.priceText.text];
}
}
and here is cellForRowAtIndexPath:
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
carCellTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
cell.nameLabel.text = [_carNames objectAtIndex:indexPath.row];
cell.priceLabel.text = [NSString stringWithFormat:#"$%#/day",[_carPrices objectAtIndex:indexPath.row]];
cell.infoLabl.text = [_carInfos objectAtIndex:indexPath.row];
switch (indexPath.row) {
case 0:
{
[cell.img setImage:[UIImage imageNamed:#"rolls.jpg"]];
return cell;
}
case 1:
{
[cell.img setImage:[UIImage imageNamed:#"bentley.jpg"]];
return cell;
}
case 2:
{
[cell.img setImage:[UIImage imageNamed:#"mercedes.jpg"]];
return cell;
}
case 3:
{
[cell.img setImage:[UIImage imageNamed:#"bmw.jpg"]];
return cell;
}
case 4:
{
[cell.img setImage:[UIImage imageNamed:#"skoda.jpg"]];
}
default:
break;
}
return cell;
}
additional:
in my tableviewCell i have a label, and a textfield. when i click on "Save" i want save all my data from textField and send it to label.
here is all code from .m file:
#import "carListViewController.h"
#import "carCellTableViewCell.h"
#import "UserSingleton.h"
#import "CheckInternetConnection.h"
#define getCarList #"http:mylink.php" //changed
#define setCarList #"http:mylink.php" //changed
#interface carListViewController ()
#property (weak, nonatomic) IBOutlet UIBarButtonItem *editButtonOutler;
- (IBAction)editButtonOnClick:(id)sender;
#property BOOL editOrSave;//0 when edit, 1 when save
#property UserSingleton * userInfo;
#property NSMutableArray *json;
#property NSMutableArray * carNames;
#property NSMutableArray * carPrices;
#property NSMutableArray * carInfos;
#property NSMutableArray * carNewPrices;
- (void) setData;
#property (weak, nonatomic) IBOutlet UITableView *meTableView;
- (void) saveDataToArray;
- (void) getDataOfCars;
#end
#implementation carListViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"List of cars";
// Do any additional setup after loading the view.
}
- (void) viewWillAppear:(BOOL)animated
{
CheckInternetConnection * checkInternet = [[CheckInternetConnection alloc] init];
if (![checkInternet isInternetAvailable])
[self.navigationController popViewControllerAnimated:YES];
_userInfo = [UserSingleton sharedInstance];
if (_userInfo.priority == 2)
{
_editButtonOutler.enabled = YES;
_editButtonOutler.title = #"Edit";
}
else
{
_editButtonOutler.enabled = NO;
_editButtonOutler.title = #"";
}
_editOrSave = NO;
[self getDataOfCars];
[_meTableView reloadData];
}
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 5;
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
carCellTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
cell.nameLabel.text = [_carNames objectAtIndex:indexPath.row];
cell.priceLabel.text = [NSString stringWithFormat:#"$%#/day",[_carPrices objectAtIndex:indexPath.row]];
cell.infoLabl.text = [_carInfos objectAtIndex:indexPath.row];
switch (indexPath.row) {
case 0:
{
[cell.img setImage:[UIImage imageNamed:#"rolls.jpg"]];
return cell;
}
case 1:
{
[cell.img setImage:[UIImage imageNamed:#"bentley.jpg"]];
return cell;
}
case 2:
{
[cell.img setImage:[UIImage imageNamed:#"mercedes.jpg"]];
return cell;
}
case 3:
{
[cell.img setImage:[UIImage imageNamed:#"bmw.jpg"]];
return cell;
}
case 4:
{
[cell.img setImage:[UIImage imageNamed:#"skoda.jpg"]];
}
default:
break;
}
return cell;
}
- (IBAction)editButtonOnClick:(id)sender {
if (_editOrSave == 0)
{
_editOrSave = 1;
_editButtonOutler.title = #"Save";
carCellTableViewCell * cell;
for (int i = 0; i < 5; i ++)
{
cell = (carCellTableViewCell *)[_meTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
cell.priceLabel.hidden = YES;
cell.priceText.hidden = NO;
cell.priceText.text = [[_json objectAtIndex:i] objectForKey:#"cost"];
}
}
else if (_editOrSave == 1)
{
_editOrSave = 0;
carCellTableViewCell * cell;
for (int i = 0; i < 5; i ++)
{
cell = (carCellTableViewCell *)[_meTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
cell.priceLabel.hidden = NO;
cell.priceText.hidden = YES;
[self saveDataToArray];
[self setData];
//cell.priceLabel.text = [_carPrices objectAtIndex:i];
}
_editButtonOutler.title = #"Edit";
}
[self getDataOfCars];
[_meTableView reloadData];
}
- (void) getDataOfCars
{
_carInfos = [[NSMutableArray alloc] init];
_carNames = [[NSMutableArray alloc] init];
_carPrices = [[NSMutableArray alloc] init];
NSURLRequest* urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:getCarList] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];
_json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
carCellTableViewCell * cell;
for (int i = 0; i < _json.count; i ++)
{
cell = (carCellTableViewCell *)[_meTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
[_carNames addObject:[[_json objectAtIndex:i] objectForKey:#"name"]];
[_carPrices addObject:[[_json objectAtIndex:i] objectForKey:#"cost"]];
[_carInfos addObject:[[_json objectAtIndex:i] objectForKey:#"about"]];
}
}
- (void) setData{
for (int i = 0; i < 5; i ++)
{
NSMutableString * postString = [NSMutableString stringWithFormat:setCarList];
[postString appendString:[NSString stringWithFormat:#"?id=%d", i+1]];
[postString appendString:[NSString stringWithFormat:#"&cost=%#", [_carPrices objectAtIndex:i]]];
[postString setString:[postString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:postString]];
[request setHTTPMethod:#"POST"];
NSURLConnection * postConnection;
postConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
}
}
- (void) saveDataToArray
{
carCellTableViewCell * cell;
_carNewPrices = [[NSMutableArray alloc] init];
for (int i = 0; i < 5; i++)
{
cell = (carCellTableViewCell *)[_meTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
[_carPrices addObject:cell.priceText.text];
}
}
#end
it seems that an error is caused because not all cells are visible in the screen. after my scroll down now even last cell has changed after my onclick on edit button.
how to resovle this problem?
It's upside-down to fill an array with what's in a UITableView. The way to do that is the other way around.
In other words, somewhere else in your code you determine what's in the priceText label. If it's a static table, then the information might be in IB, or if you're implementing tableview:cellForRowAtIndexPath:, you're looking up the priceText there.
Put those values in the priceArray.
Your edit helped. This line:
[NSString stringWithFormat:#"$%#/day",[_carPrices objectAtIndex:indexPath.row]];
Is your friend, so:
NSMutableArray *newArrayOfStrings = [NSMutableArray array];
for (int i=0; i<_carPrices.count; i++) {
NSString *str = [NSString stringWithFormat:#"$%#/day",_carPrices[i]];
[newArrayOfStrings addObject:str];
}
Edit again. More code and comments, more clarity:
Declare that your vc implements the UITextFieldDelegate, and declare a property to keep your edited prices:
#interface MyViewController <UITextFieldDelegate>
#property (nonatomic, strong) NSMutableArray *editedStrings;
// initialize this with the carPrices after you get these from JSON
self.editedStrings = [_carPrices mutableCopy]; // if they are NSNumbers
// if they are strings, you'll need a deeper copy:
self.editedStrings = [NSMutableArray array];
for (NSString *str in _carPrices) {
[self.editedStrings addObject:[str copy]];
}
In cellForRowAtIndexPath, make your vc the delegate, and tag the textFields, so you know which one is being edited:
cell.priceLabel.delegate = self;
cell.priceLabel.tag = indexPath.row;
Then implement the delegate method for when the user edits:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSInteger index = textField.tag;
NSString *candidateString = [textField.text stringByReplacingCharactersInRange:range withString:string];
[self.editedStrings replaceObjectAtIndex:index withObject: candidateString];
return YES;
}
Add a breakpoint to the line [_carPrices addObject:cell.priceText.text] and you'll see that at some index, the text will be nil. I can't tell you why will it be nil, since I don't know how you're creating the cell.

Getting '-[__NSArrayM city]: unrecognized selector sent to instance 0x111c03460' error

I'm trying to use Google's geocoding api to get the city name and geolocation. But I'm getting this error and don't know which part I go wrong. Could anyone please help?
Here's my code:
ViewController:
- (void)searchCityGeoLocationByName:(NSString *)name
{
[self.searchResults removeAllObjects];
NSString *requestUrl = [[NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/geocode/json?address=%#&sensor=true&key=%#", name, GOOGLE_GEOCODING_API_KEY] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:requestUrl
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)operation.response;
if (httpResponse.statusCode == 200) {
dispatch_async(dispatch_get_main_queue(), ^{
NSMutableArray *results = [NSMutableArray array];
for (id response in [responseObject objectForKey:#"results"]) {
self.search = [[Search alloc] initWithDictionary:response];
[results addObject:self.search];
}
self.searchResults = [NSMutableArray arrayWithCapacity:results.count];
for (int i = 0; i < results.count; i++) {
[self.searchResults addObject:results];
}
[self.searchController.searchResultsTableView reloadData];
});
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"SearchCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Search *search = [self.searchResults objectAtIndex:indexPath.row];
cell.textLabel.text = search.city;
return cell;
}
Search.h:
#interface Search : NSDictionary
- (id)initWithDictionary:(NSDictionary *)otherDictionary;
#property (nonatomic, strong) NSString *city;
#property (nonatomic, strong) NSString *lat;
#property (nonatomic, strong) NSString *lng;
#end
Search.m:
- (id)initWithDictionary:(NSDictionary *)otherDictionary
{
self = [super init];
if (self) {
self.city = [otherDictionary objectForKey:#"formatted_address"];
self.lat = [[otherDictionary valueForKeyPath:#"geometry.location"] objectForKey:#"lat"];
self.lng = [[otherDictionary valueForKeyPath:#"geometry.location"] objectForKey:#"lng"];
}
return self;
}
Thanks for your help.
Change this:
for (int i = 0; i < results.count; i++) {
[self.searchResults addObject:results];
}
to:
for (int i = 0; i < results.count; i++) {
[self.searchResults addObject:results[i]];
}
you adding array to self.searchResults and try to get Search object.
Replace
self.searchResults = [NSMutableArray arrayWithCapacity:results.count];
for (int i = 0; i < results.count; i++) {
[self.searchResults addObject:results];
}
With:
self.searchResults = results;
You can also just remove the results variable and use directly the self.searchResults variable instead.
When you are adding objects to self.searchResults you are adding the NSMutableArray results each time, so then in cellForRowAtIndexPath: when you try to assign search to:
Search *search = [self.searchResults objectAtIndex:indexPath.row];
Instead you are returning an NSMutableArray, so on the next line, when you try to access the search.city the object is an array, rather than a Search object.
You need to look at whether these lines are correct:
for (int i = 0; i < results.count; i++) {
[self.searchResults addObject:results];
}
Are you sure you want to be adding results there? Is an NSMutableArray of NSMutableArrays what you want self.searchResults to contain?
You probably want to replace it with something like this:
[self.searchResults addObject:results[i]];

TableView does not reloaddata when I clicked "More data..." at the last row of tableView

Request my test webService for the data,
The tableView's last row is "More data..."
when click this row, send another request to get more data,
and I use [tableView reloaddata] many times, but there is nothing
happened, and I dont know why.So,please help me with this problem.
Thank you in advance.
and there is my tableViewController.h class:
#import <UIKit/UIKit.h>
#import "NoticeDetailViewController.h"
#interface NoticeViewController : UIViewController
<UITableViewDataSource,UITableViewDelegate>
{
NSMutableArray *allNoticeArray;
NSArray *addNoticeArray;
NSInteger totalNotice;
NSInteger pageIndex;
UITableView *tableView;
}
#property (nonatomic, retain) NSMutableArray *allNoticeArray;
#property (nonatomic, retain) NSArray *addNoticeArray;
#property NSInteger totalNotice;
#property NSInteger pageIndex;
#property (nonatomic, retain) UITableView *tableView;
- (NSMutableArray *)getNoticeList :(NSInteger)pageIndex;
#end
And tableViewController.m class:
#import "NoticeViewController.h"
#import "Notice.h"
#import "OAURLEncodingAdditions.h"
#interface NoticeViewController ()
#end
#implementation NoticeViewController
#synthesize allNoticeArray;
#synthesize addNoticeArray;
#synthesize pageIndex;
#synthesize tableView;
#synthesize totalNotice;
- (NSMutableArray *)getNoticeList :(NSInteger)pageIndex
{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *userId = appDelegate.user.userId;
NSString *departmentId = appDelegate.user.departmentId;
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://xxx.xxx.xx.xx/FMS/Pages/Service/FMService.svc/GetAnnouncement?userId=%#&departmentId=%#&pageIndex=%d&pageSize=%d",userId,departmentId,self.pageIndex,1]];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setValidatesSecureCertificate:NO];
[request startSynchronous];
NSError *error = [request error];
if (!error)
{
NSString *responseString = [request responseString];
NSDictionary *responseDict = [responseString JSONValue];
NSArray *noticeArray = [responseDict objectForKey:#"d"];
NSMutableArray *arrayOfAllNotice = [[NSMutableArray alloc] init];
for (NSDictionary *noticeDic in noticeArray)
{
NSString *body = [noticeDic objectForKey:#"Body"];
NSString *departmentName = [noticeDic objectForKey:#"DepartmentName"];
NSString *noticeId = [noticeDic objectForKey:#"Id"];
NSString *isTop = [noticeDic objectForKey:#"IsTop"];
NSString *readState = [noticeDic objectForKey:#"ReadState"];
NSString *realName = [noticeDic objectForKey:#"RealName"];
NSString *title = [noticeDic objectForKey:#"Title"];
int noid = [noticeId intValue];
int isto = [isTop intValue];
int read = [readState intValue];
Notice *notice = [[Notice alloc] initWithBody:body
departmentName:departmentName
noticeId: noid
isTop:isto
readState:read
realName:realName
title:title];
[arrayOfAllNotice addObject:notice];
}
self.addNoticeArray = [[NSArray alloc] initWithArray:arrayOfAllNotice];
}
else
{
....
}
[allNoticeArray addObjectsFromArray:addNoticeArray];
NSLog(#"allNoticeArray count: %d",[allNoticeArray count]); //Here:When the last row clicked, the number changes:1->2
[self.tableView reloadData];
return allNoticeArray;
}
#pragma mark -
#pragma mark Table View Data Source Methods
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger theNumberOfRowsInSection;
if ( [allNoticeArray count] < (self.totalNotice))
{
theNumberOfRowsInSection = [allNoticeArray count]+1;
}
if ( [allNoticeArray count] == (self.totalNotice))
{
theNumberOfRowsInSection = [allNoticeArray count];
}
return theNumberOfRowsInSection;
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.tableView reloadData];
static NSString *NoticeListTableIdentifier = #"NoticeListTableIdentifier";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:NoticeListTableIdentifier];
if ( cell == nil )
{
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NoticeListTableIdentifier] autorelease];
}
if ( [allNoticeArray count] < (self.totalNotice) )
{
if ( [indexPath row] != [allNoticeArray count])
{
NSUInteger row = [indexPath row];
Notice *noticeOfTheRow = [allNoticeArray objectAtIndex:row];
NSString *title = noticeOfTheRow.title;
cell.textLabel.text = title;
}
else
{
cell.textLabel.text = #"More...";
}
}
if ( [allNoticeArray count] == (self.totalNotice) )
{
NSUInteger row = [indexPath row];
Notice *noticeOfTheRow = [allNoticeArray objectAtIndex:row];
NSString *title = noticeOfTheRow.title;
cell.textLabel.text = title;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ( [indexPath row] != [allNoticeArray count])
{
NSUInteger row = [indexPath row];
Notice *notice = [allNoticeArray objectAtIndex:row];
NSString *noticeDetailTitle = notice.title;
NoticeDetailViewController *noticeDetailViewController = [[[NoticeDetailViewController alloc] init] autorelease];
noticeDetailViewController.title = noticeDetailTitle;
ticeDetailViewController.noticeIdForGet = notice.noticeId;
[self.navigationController pushViewController:noticeDetailViewController animated:YES];
}
if ( [indexPath row] == [allNoticeArray count])
{
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.labelText = #"reload...";
self.pageIndex ++;
[self getNoticeList:self.pageIndex];
[self.tableView reloadData];
[MBProgressHUD hideHUDForView:self.view animated:YES];
}
}
- (void)pushBack
{
[self dismissModalViewControllerAnimated:YES];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.allNoticeArray = [[NSMutableArray alloc] init];
self.pageIndex = 1;
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.labelText = #"reload...";
self.title = #"Notice";
UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:#"back"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(pushBack)];
self.navigationItem.leftBarButtonItem = leftButton;
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:#"reload"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(reloadNotice)];
self.navigationItem.rightBarButtonItem = rightButton;
self.allNoticeArray = [self getNoticeList:self.pageIndex];
[MBProgressHUD hideHUDForView:self.view animated:YES];
}
#end
change:
if ( [indexPath row] == [allNoticeArray count])
to:
if ( [indexPath row] == [allNoticeArray count]-1)
The reason is that array (and row) indexing are base 0. So if an array has, say 3 objects, last object's index is 2
BTW,with the new language features, there's no need to declare the ivars in the interface. The compiler will take care of them if you have already declared the properties and synthesized them.
#interface NoticeViewController : UIViewController
<UITableViewDataSource,UITableViewDelegate>
{
NSMutableArray *allNoticeArray;
NSArray *addNoticeArray;
NSInteger totalNotice;
NSInteger pageIndex;
UITableView *tableView;
}
//...
#end

Resources