Json issue in tableview with stepper and lable - ios

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.

Related

iOS: why second section is not displayed in UITableView?

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

Label data is erased when I back to the screen from tableview in iOS

Here is my JSON response with label value.
{
"Dry_cleaning" = 49;
Iron = 8;
Name = "Shirt/Tees";
Wash = 15;
"Wash_Iron" = 19;
counts = 2;
id = 1;
total = 98;
},
{
"Dry_cleaning" = 49;
Iron = 5;
Name = "Kurta(short)";
Wash = 20;
"Wash_Iron" = 19;
counts = 2;
id = 2;
total = 98;
},
{
"Dry_cleaning" = 50;
Iron = 8;
Name = "Kurta(Long)";
Wash = 15;
"Wash_Iron" = 20;
counts = 0;
id = 3;
},
{
"Dry_cleaning" = 50;
Iron = 5;
Name = Shorts;
Wash = 15;
"Wash_Iron" = 19;
counts = 0;
id = 4;
},
{
"Dry_cleaning" = 55;
Iron = 8;
Name = "Trousers/Pyjamas";
Wash = 20;
"Wash_Iron" = 30;
counts = 0;
id = 5;
},
{
"Dry_cleaning" = 70;
Iron = 7;
Name = Jeans;
Wash = 20;
"Wash_Iron" = 29;
counts = 0;
id = 6;
},
{
"Dry_cleaning" = 150;
Iron = 5;
Name = Blazer;
Wash = 25;
"Wash_Iron" = 19;
counts = 0;
id = 7;
},
{
"Dry_cleaning" = 100;
Iron = 6;
Name = "Leather_Jacket";
Wash = 30;
"Wash_Iron" = 36;
counts = 0;
id = 8;
},
{
"Dry_cleaning" = 100;
Iron = 13;
Name = "Lungi/Dhoti(Long)";
Wash = 12;
"Wash_Iron" = 15;
counts = 0;
id = 9;
},
Here is my first screenshot:
I will complete increment in specific cell. When I click the place order button then display total amount screen.
Second screenshot:
Third screenshot:
When I back to the screen the stepper label value is zero. But I want editable value in specific cell.
Here is my code.
order.h
#import <UIKit/UIKit.h>
#import "customcell.h"
#interface order : UIViewController<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
#property (weak, nonatomic) IBOutlet UITableView *tableview;
- (IBAction)placeorder:(id)sender;
#property (weak, nonatomic) IBOutlet UIButton *btn_placeorder;
#end
order.m
//
// order.m
// laundryapp
//
// Created by Tranetech on 13/01/16.
// Copyright (c) 2016 Tranetech. All rights reserved.
//
#import "order.h"
#import "customcell.h"
#import "totalamount.h"
#import "globalvariabe.h"
#interface order ()
#end
#implementation order
{
NSDictionary *dic_property;
// NSArray *dic_property;
NSMutableDictionary *data;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableview reloadData];
globalvariabe *global=[globalvariabe sharedInstance];
[NSThread detachNewThreadSelector:#selector(fetchdata) toTarget:self withObject:nil];
global.arrayCounts = [NSMutableArray array];
// NSLog(#"array count=%lu",(unsigned long)global.arrayCounts.count);
// [self.tableview registerNib:[UINibnibWithNibName:#"customcell"bundle:nil] forCellReuseIdentifier:#"Cell"];
// Do any additional setup after loading the view.
}
-(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];
// }
NSArray *tempArray = dic_property[#"Data"];
for (int i=0; i<tempArray.count; i++) {
NSMutableDictionary *dictValues = [NSMutableDictionary dictionaryWithDictionary:tempArray[i]];
[dictValues setValue:#"0" forKey:#"counts"];
globalvariabe *global=[globalvariabe sharedInstance];
[global.arrayCounts addObject:dictValues];
}
[self.tableview reloadData];
}
else {
NSLog(#"network error, %#", [error localizedFailureReason]);
}
});
}];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 100;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
globalvariabe *global=[globalvariabe sharedInstance];
return global.arrayCounts.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableItem";
customcell *cell = (customcell *)[self.tableview dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
cell = [[[NSBundle mainBundle] loadNibNamed:#"customcell" owner:self options:nil] objectAtIndex:0];
globalvariabe *global=[globalvariabe sharedInstance];
// NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
// NSMutableArray *test=[userDefaults objectForKey:#"finalarray"];
cell.lbl_value.text = [NSString stringWithFormat:#"%#",global.arrayCounts[indexPath.row][#"counts"]];
NSLog(#"strainfffdf=%#",[NSString stringWithFormat:#"%#",global.arrayCounts[indexPath.row][#"counts"]]);
cell.lbl_title.text=[NSString stringWithFormat:#"%#",global.arrayCounts[indexPath.row][#"Name"]];
cell.lbl_price.text=[NSString stringWithFormat:#"%#",global.arrayCounts[indexPath.row][#"Dry_cleaning"]];
cell.txt1.text=[NSString stringWithFormat:#"%#",global.arrayCounts[indexPath.row][#"counts"]];
[cell.stepper addTarget:self action:#selector(itemsChange:) forControlEvents:UIControlEventValueChanged];
return cell;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
- (void)itemsChange:(UIStepper*)stepper
{
CGPoint cursorPosition = [stepper convertPoint:CGPointZero toView:self.tableview];
NSIndexPath *indexPath = [self.tableview indexPathForRowAtPoint:cursorPosition];
customcell *currentCell = (customcell *)[self.tableview cellForRowAtIndexPath:indexPath];
double value = [stepper value];
int x = [currentCell.lbl_value.text intValue];
int price=[currentCell.lbl_price.text intValue];
int y= x * price;
[currentCell.lbl_value setText:[NSString stringWithFormat:#"%d", (int)value]];
currentCell.txt1.text=[NSString stringWithFormat:#"%d", (int)value];
globalvariabe *global=[globalvariabe sharedInstance];
global.arrayCounts[indexPath.row][#"counts"] = [NSString stringWithFormat:#"%d",(int)value];
global.arrayCounts[indexPath.row][#"total"] = [NSString stringWithFormat:#"%d",(int)y];
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
- (IBAction)placeorder:(id)sender {
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"counts != %#",#"0"];
globalvariabe *global=[globalvariabe sharedInstance];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
global.filteredArray = [global.arrayCounts filteredArrayUsingPredicate:predicate];
NSLog(#"button click event=%#",global.arrayCounts);
if(global.filteredArray.count > 0)
{
[userDefaults setObject:global.filteredArray forKey:#"def_orderarraylist"];
[userDefaults setObject:global.arrayCounts forKey:#"finalarray"];
[userDefaults synchronize];
}
// NSLog(#"value:%#",global.filteredArray);
NSLog(#"default array=%#",[userDefaults objectForKey:#"finalarray"]);
totalamount *nextpage=[self.storyboard instantiateViewControllerWithIdentifier:#"totalamountpage"];
[self presentViewController:nextpage animated:YES completion:nil];
}
#end
How to get my editable label value when I return to the screen?
Instead of calling fetchdata method in -(void)viewDidLoad method, you should call that method in -(void)viewWillAppear:(BOOL)animated method. And use [self.navigationController popViewControllerAnimated:YES] to go back from viewcontroller.

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.

UITableView with Json file, loading images to cell disappear

I am using asyncimageview classes nicely provided by: http://www.markj.net/iphone-asynchronous-table-image/
I am getting image urls from a json file and loading each image to a cell.
Problem:
When i scroll up, and scroll back down to the same cell, the image reloads (disappears and appears again). I can't figure out why the image keeps reloading? Does anyone have suggestions or a solution to how I could make it stop? Thanks in advance!
// Asks the data source to return a cell to insert in a particular table view location
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//Gets the current news article
NewsArticle *theCurrentArticle = [self.listofNewsArticles objectAtIndex:[indexPath row]];
//Gets the title from the current article
NSString *theTitle = theCurrentArticle.title;
//Gets the image url
NSString *imageUrl = theCurrentArticle.imageURL;
//Gets the description of the current news article
NSString *theDescription = theCurrentArticle.description;
NewsCustomCell *cell = (NewsCustomCell *)[tableView dequeueReusableCellWithIdentifier:#"NewsContent"];
__block NewsCustomCell *aCell;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
if (cell == nil) {
aCell = (NewsCustomCell *)[tableView dequeueReusableCellWithIdentifier:#"NewsContent"];
} else {
AsyncImageView* oldImage = (AsyncImageView*)
[cell.contentView viewWithTag:999];
[oldImage removeFromSuperview];
}
AsyncImageView *imageView = [[AsyncImageView alloc] initWithFrame:CGRectMake(5, 5, 100, 100)];
imageView.tag = 999;
dispatch_async(dispatch_get_main_queue(), ^{
[imageView loadImageFromURL:[NSURL URLWithString:imageUrl]];
[cell.contentView addSubview:imageView];
cell.titleLabel.text = theTitle;
cell.descriptionLabel.text = theDescription;
cell.imageLabel.contentMode = UIViewContentModeScaleAspectFill;
});
});
return cell;
}
Heres what the current app looks like:
Solution:
Just worked with this class I finally found.
https://github.com/rs/SDWebImage
This handles caching, async downloads. Wish I found this sooner..
I hope you have Write AsyncImageView and ImageCache and ImageCacheObject classes.
Write this code inside cellForRowAtIndexPath:
static NSString *CellIdentifier = #"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Quest_Forum *Quest_ForumObj=[queArr objectAtIndex:i+indexPath.row];
// NSLog(#"cell for row at... i val.. %d",i+indexPath.row);
for(UIView * view in cell.contentView.subviews){
if([view isKindOfClass:[AsyncImageView class]])
{
// NSLog(#"remove old images");
[view removeFromSuperview];
view = nil;
}
}
AsyncImageView *asyncImageView = nil;
UIImageView *cellImage = (UIImageView *)[cell viewWithTag:1]; // Inside tableview i have taken tableviewcell and given tag 1 to that imageview
asyncImageView = [[AsyncImageView alloc] initWithFrame:cellImage.frame] ;
[asyncImageView loadImageFromURL:Quest_ForumObj.Quest_Image];
asyncImageView.backgroundColor=[UIColor clearColor];
[cell.contentView addSubview:asyncImageView];
UILabel *lblQuest = (UILabel *)[cell viewWithTag:2]; // Given tag 2 to the label inside tableViewCell
lblQuest.text=Quest_ForumObj.Question;
In ImageCacheObject.h
#class ImageCacheObject;
#interface ImageCache : NSObject
{
NSUInteger totalSize; // total number of bytes
NSUInteger maxSize; // maximum capacity
NSMutableDictionary *myDictionary;
}
#property (nonatomic, readonly) NSUInteger totalSize;
-(id)initWithMaxSize:(NSUInteger) max;
-(void)insertImage:(UIImage*)image withSize:(NSUInteger)sz forKey:(NSString*)key;
-(UIImage*)imageForKey:(NSString*)key;
In ImageCacheObject.m
#import "ImageCacheObject.h"
#synthesize totalSize;
-(id)initWithMaxSize:(NSUInteger) max
{
if (self = [super init])
{
totalSize = 0;
maxSize = max;
myDictionary = [[NSMutableDictionary alloc] init];
}
return self;
}
-(void)dealloc // Don't write this method if you are using ARC
{
[myDictionary release];
[super dealloc];
}
-(void)insertImage:(UIImage*)image withSize:(NSUInteger)sz forKey:(NSString*)key
{
// NSLog(#"count of insert image%d",sz);
ImageCacheObject *object = [[ImageCacheObject alloc] initWithSize:sz Image:image];
while (totalSize + sz > maxSize)
{
NSDate *oldestTime;
NSString *oldestKey;
for (NSString *key in [myDictionary allKeys])
{
ImageCacheObject *obj = [myDictionary objectForKey:key];
if (oldestTime == nil || [obj.timeStamp compare:oldestTime] == NSOrderedAscending)
{
oldestTime = obj.timeStamp;
oldestKey = key;
}
}
if (oldestKey == nil)
break; // shoudn't happen
ImageCacheObject *obj = [myDictionary objectForKey:oldestKey];
totalSize -= obj.size;
[myDictionary removeObjectForKey:oldestKey];
}
[myDictionary setObject:object forKey:key];
[object release];
}
-(UIImage*)imageForKey:(NSString*)key
{
ImageCacheObject *object = [myDictionary objectForKey:key];
if (object == nil)
return nil;
[object resetTimeStamp];
return object.image;
}
In ImageCacheObject.h
#interface ImageCacheObject : NSObject
{
NSUInteger size; // size in bytes of image data
NSDate *timeStamp; // time of last access
UIImage *image; // cached image
}
#property (nonatomic, readonly) NSUInteger size;
#property (nonatomic, retain, readonly) NSDate *timeStamp;
#property (nonatomic, retain, readonly) UIImage *image;
-(id)initWithSize:(NSUInteger)sz Image:(UIImage*)anImage;
-(void)resetTimeStamp;
In ImageCacheObject.m
#synthesize size;
#synthesize timeStamp;
#synthesize image;
-(id)initWithSize:(NSUInteger)sz Image:(UIImage*)anImage
{
if (self = [super init])
{
size = sz;
timeStamp = [[NSDate date] retain];
image = [anImage retain];
}
return self;
}
-(void)resetTimeStamp
{
[timeStamp release];
timeStamp = [[NSDate date] retain];
}
-(void) dealloc
{
[timeStamp release];
[image release];
[super dealloc];
}

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