NSSortDescriptor doesn't update UITableView - ios

I'm trying to sort my tableview using NSSortDescriptor in a UISegmentedControl. When I log the Array to sort it shows the correct sorting order, but the tableview doesn't update after calling [self.tableView reloadData];
The data comes from an array which is populated by a json feed. I'm not using NSObjects to display the tableview, it's all populated from the NSArray. See code below:
#interface LinksTableViewController (){
NSArray *data;
}
#property (strong, nonatomic) NSArray *links;
#property (strong, nonatomic) NSArray *tNames;
#property (strong, nonatomic) NSArray *dThor;
#property (strong, nonatomic) NSArray *theLinker;
#property (strong, nonatomic) NSArray *anText;
#property (strong, nonatomic) NSArray *noDo;
#end
#implementation LinksTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
UISegmentedControl *statFilter = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:#"STAT1", #"STAT2", #"STAT3", #"STAT4", nil]];
[statFilter sizeToFit];
[statFilter addTarget:self action:#selector(MySegmentControlAction:) forControlEvents: UIControlEventValueChanged];
self.navigationItem.titleView = statFilter;
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(refreshdelay:) userInfo:nil repeats:NO];
}
- (void)MySegmentControlAction:(UISegmentedControl *)segment
{
NSArray *arrayToSort = data;
if (segment.selectedSegmentIndex == 0)
{
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"pda" ascending:NO];
arrayToSort = [arrayToSort sortedArrayUsingDescriptors:#[sortDescriptor]];
NSLog(#"%#", arrayToSort);
}
else if (segment.selectedSegmentIndex == 1)
{
}
else if (segment.selectedSegmentIndex == 2)
{
}
else if (segment.selectedSegmentIndex == 3)
{
}
[self.tableView reloadData];
}
-(void)refreshdelay:(NSTimer*)timer
{
NSString *myString = [links absoluteString];
NSURL *JSONData = [NSURL URLWithString:myString];
NSData *datas = [NSData dataWithContentsOfURL:JSONData];
NSURLRequest *request = [NSURLRequest requestWithURL:JSONData];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
operation.responseSerializer.acceptableContentTypes = [operation.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSArray *jsonResult = [NSJSONSerialization JSONObjectWithData:datas options:kNilOptions error:nil];
data = jsonResult;
NSMutableArray *names = [NSMutableArray array];
NSMutableArray *bLinks = [NSMutableArray array];
NSMutableArray *daThor = [NSMutableArray array];
NSMutableArray *bsLink = [NSMutableArray array];
NSMutableArray *ancTxt = [NSMutableArray array];
NSMutableArray *folLowd = [NSMutableArray array];
for (id itemfeed in jsonResult){
[names addObject:[NSString stringWithFormat:#"%#", itemfeed[#"ut"]]];
[bsLink addObject:[NSString stringWithFormat:#"%#", itemfeed[#"uu"]]];
[bLinks addObject:[NSString stringWithFormat:#"%#", itemfeed[#"upa"]]];
[daThor addObject:[NSString stringWithFormat:#"%#", itemfeed[#"pda"]]];
[ancTxt addObject:[NSString stringWithFormat:#"%#", itemfeed[#"lt"]]];
[folLowd addObject:[NSString stringWithFormat:#"%#", itemfeed[#"lf"]]];
self.links = names;
self.tNames = bLinks;
self.dThor = daThor;
self.theLinker = bsLink;
self.anText = ancTxt;
self.noDo = folLowd;
}
[self.tableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
[operation start];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
static NSString *Cellidentifier = #"DataTableCellId";
LICustomCell *cell = (LICustomCell *) [tableView dequeueReusableCellWithIdentifier:Cellidentifier];
if (cell == nil) {
cell = [[LICustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Cellidentifier];
NSArray *nib = [[NSBundle mainBundle]loadNibNamed:#"LiCellView" owner:self options:nil];
cell = nib[0];
NSString *sLink = self.links[indexPath.row];
NSString *aLink = self.tNames[indexPath.row];
NSString *aDa = self.dThor[indexPath.row];
NSString *theInk = self.theLinker[indexPath.row];
NSString *thAnk = self.anText[indexPath.row];
NSString *fLink = self.noDo[indexPath.row];
cell.ageLable.text = theInk;
}
return cell;
}

Looks like the data for your tableView is in 6 different arrays.
NSString *sLink = self.links[indexPath.row];
NSString *aLink = self.tNames[indexPath.row];
NSString *aDa = self.dThor[indexPath.row];
NSString *theInk = self.theLinker[indexPath.row];
NSString *thAnk = self.anText[indexPath.row];
NSString *fLink = self.noDo[indexPath.row];
Shouldn't you be sorting all of them? As your code stands now it's not clear how arrayToSort is connected to the data model of your tableView. You have NSArray *arrayToSort = data;, but it's not clear where data is initialized or where it's set (seems like you would want to set that in your JSON competition block). You also need to call [self.tableView reloadData]; at the end of MySegmentControlAction.
You can create a subclass of NSObject that has 6 NSString properties call it something like MyObject (but more descriptive). Then do something like:
for (id itemfeed in jsonResult){
MyObject *object = [[MyObject alloc]init];
object.sLink = [NSString stringWithFormat:#"%#", itemfeed[#"ut"]];
object.aLink = [NSString stringWithFormat:#"%#", itemfeed[#"uu"]];
...
[self.data addObject:object];
}
In the JSON competition block.
You then change cellForRowAtIndexPath to include something like
MyObject *object = [self.data objectAtIndex:indexPath.row]
cell.ageLable.text = object.theInk;
If you go this route you also need to update:
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"pda" ascending:NO];
specifically #"pda" to whatever you name the property in your NSObject subclass. #"dThor" if you follow the naming I used.

Related

How to add string containing array in NSMutable Array?

I have this json
{
"title": "xyz",
"category": "Monetary",
"target": "55",
"achieve": "0",
"todolist": [
{
"todoitem": "one"
},
{
"todoitem": "two"
},
{
"todoitem": "three"
}
]
}
coming from API and I want to add todolist array to
In .h file
#property (strong, nonatomic) NSMutableArray *todolist;
#property (strong, nonatomic) NSMutableArray *todolists;
#property (strong, nonatomic) NSMutableArray *listnumber;
In .m file
todolist=[[NSMutableArray alloc] initWithObjects: nil];
todolists=[[NSMutableArray alloc] initWithObjects: nil];
listnumber=[[NSMutableArray alloc] initWithObjects: nil];
In function getting json
todolists = [result valueForKey:#"todolist"];
for (int j =0; j < todolist.count; j++)
{
[todolist addObject:[[todolists objectAtIndex:j] valueForKey:#"todoitem"]];
[listnumber addObject:[NSString stringWithFormat:#"%d", j]];
}
[tvToDoList reloadData];
CellForRowAtIndexPath I am adding values two field
static NSString *CellIdentifier=#"Cell";
TodolistTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if(cell==nil)
{
cell = [[TodolistTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier ];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
int row = (int)[indexPath row];
cell.valListitem.text = todolist[row];
cell.lblNo.text = listnumber[row];
return cell;
}
where result is containing the whole json
Try this in one line code.
todolist = [[[result valueForKey:#"todolist"] valueForKey:#"todoitem"] mutableCopy];
If you want to get string from array here is solution
for (int i =0; i < listnumber.count; i++)
{
[todolist addObject:[[listnumber objectAtIndex:i] valueForKey:#"todoitem"]];
}
Parse your json string and get the todos as NSArray from that.
#Try this
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
id object = [NSJSONSerialization
JSONObjectWithData:data
options:0
error:&error];
NSArray *todos = [object valueForKey:#"todolist"];
NSMutableArray *mutableToDos = [[NSMutableArray alloc] initWithArray:todos];
Here is the code for display in cell
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSDictionary *todo = [mutableToDos objectAtIndex:indexPath.row];
[[cell textLabel] setText:[todo valueForKey:#"todoitem"];
return cell;
}
Try this
#property (strong, nonatomic) NSMutableArray *todolist;
todolist=[[NSMutableArray alloc] initWithObjects: nil];
//Convert to NSData
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
//JSON object
id object = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//Array of ToDo List
NSArray *list = (NSArray *)[object valueForKey:#"todolist"];
//Fetch items of ToDo List
for (int i =0; i < [list count]; i++)
{
[todolist addObject:[[list objectAtIndex:i] valueForKey:#"todoitem"]];
}
NSLog(#"Array :: %#", todolist);
Hopefully, this will help you.
Thanks.

Mutable Array sometimes working for images in UITableView

I am getting a very strange array issue with LogoURL. Sometimes it works and sometimes it errors when trying to display the URL's in the array as an image. This is an Mutable array problem and its driving me crazy.
import "ViewController.h"
#interface ViewController ()
#property (nonatomic, strong) MSTable *table;
#property (nonatomic, strong) NSMutableArray *items;
#property (weak, nonatomic) IBOutlet UITableView *MainTableView;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// create the activity indicator in the main queue
self.MainTableView.hidden = YES;
UIActivityIndicatorView *ac = [[UIActivityIndicatorView alloc]
initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[self.view addSubview:ac];
[ac startAnimating];
self.client = [MSClient clientWithApplicationURLString:#"https://mobile.net/" applicationKey:#""];
self.table = [self.client tableWithName:#"notifications"];
self.logoURL = [[NSMutableArray alloc] init];
self.rowitems = [[NSMutableArray alloc] init];
MSQuery *query = [self.table query];
query.fetchLimit = 3;
[query readWithCompletion:^(NSArray *items, NSInteger totalCount, NSError *error)
{
self.rowitems = [items mutableCopy];
//[self.MainTableView reloadData];
int a;
for (a = 0; a < 3; a++)
{
NSDictionary *apt = [self.rowitems objectAtIndex:a];
NSLog(#"%#", apt[#"barID"]);
NSDictionary *barIDDictionary = #{ #"myParam": apt[#"barID"]};
self.client = [MSClient clientWithApplicationURLString:#"https://outnight-mobile.azure-mobile.net/" applicationKey:#"okYeRGfBagYrsbkaqWIRObeDtktjkF10"];
[self.client invokeAPI:#"photos" body:barIDDictionary HTTPMethod:#"POST" parameters:nil headers:nil completion:^(id result, NSHTTPURLResponse *response, NSError *error) {
if (error) {
NSLog(#"Error %#", error );
}
else {
NSString *string = [NSString stringWithFormat:#"%#", [result objectForKey:#"rows"]];
NSString *stringWithoutbracketsend = [string stringByReplacingOccurrencesOfString:#")" withString:#""];
NSString *stringWithoutbracketsfront = [stringWithoutbracketsend stringByReplacingOccurrencesOfString:#"(" withString:#""];
NSString *completion = [stringWithoutbracketsfront stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *newStr = [completion substringFromIndex:1];
NSString *finalstring = [newStr substringToIndex:newStr.length-(newStr.length>0)];
[self.logoURL insertObject:finalstring atIndex:a];
[self.MainTableView reloadData];
}
}];
}
}];
self.MainTableView.hidden = NO;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.rowitems count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
NSDictionary *stress = [self.rowitems objectAtIndex:indexPath.row];
cell.textLabel.text = stress[#"content"];
if (self.logoURL.count > indexPath.row) {
[cell.imageView setImageWithURL:[NSURL URLWithString:self.logoURL[indexPath.row]] placeholderImage:[UIImage imageNamed:#"greybox40.png"]];
NSLog(#"%#", self.logoURL[indexPath.row]);
}
else
cell.imageView.image = nil;
return cell;
}
#end
I need some fresh eyes on it, can anyone advice ?
thanks
I don’t know much about MSQuery, but if the completion block can be in a separate thread, this is going to mess you up.
The tableView can call -tableView:numberOfRowsInSection: when you have some number of rows, and then call -tableView:cellForRowAtIndexPath: when there’s a totally different number.
Also I don’t know what MSClient is, but if it’s running its completion block in a background thread you’re reloading your tableView in a background thread, so that’s gonna kill you, too.

NSMutable Array problems

All,
I have an issue with my NSMutable array LogoURL. when the UITable reloads it only shows at array location [0] and not at [1] or [2]. Here is my code, can someone look at see where I am going wrong. Its very minor problem but its driving me crazy!
#import "ViewController.h"
#interface ViewController ()
#property (nonatomic, strong) MSTable *table;
#property (nonatomic, strong) NSMutableArray *items;
#property (weak, nonatomic) IBOutlet UITableView *MainTableView;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// create the activity indicator in the main queue
self.MainTableView.hidden = YES;
UIActivityIndicatorView *ac = [[UIActivityIndicatorView alloc]
initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[self.view addSubview:ac];
[ac startAnimating];
self.client = [MSClient clientWithApplicationURLString:#"https://outnight-mobile.azure-mobile.net/" applicationKey:#"okYeRGfBagYrsbkaqWIRObeDtktjkF10"];
self.table = [self.client tableWithName:#"notifications"];
self.logoURL = [[NSMutableArray alloc] init];
self.rowitems = [[NSMutableArray alloc] init];
MSQuery *query = [self.table query];
query.fetchLimit = 3;
[query readWithCompletion:^(NSArray *items, NSInteger totalCount, NSError *error)
{
self.rowitems = [items mutableCopy];
//[self.MainTableView reloadData];
int a;
for (a = 0; a < 3; a++)
{
NSDictionary *apt = [self.rowitems objectAtIndex:a];
NSLog(#"%#", apt[#"barID"]);
NSDictionary *barIDDictionary = #{ #"myParam": apt[#"barID"]};
self.client = [MSClient clientWithApplicationURLString:#"https://outnight-mobile.azure-mobile.net/" applicationKey:#"okYeRGfBagYrsbkaqWIRObeDtktjkF10"];
[self.client invokeAPI:#"photos" body:barIDDictionary HTTPMethod:#"POST" parameters:nil headers:nil completion:^(id result, NSHTTPURLResponse *response, NSError *error) {
if (error) {
NSLog(#"Error %#", error );
}
else {
NSString *string = [NSString stringWithFormat:#"%#", [result objectForKey:#"rows"]];
NSString *stringWithoutbracketsend = [string stringByReplacingOccurrencesOfString:#")" withString:#""];
NSString *stringWithoutbracketsfront = [stringWithoutbracketsend stringByReplacingOccurrencesOfString:#"(" withString:#""];
NSString *completion = [stringWithoutbracketsfront stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *newStr = [completion substringFromIndex:1];
NSString *finalstring = [newStr substringToIndex:newStr.length-(newStr.length>0)];
[self.logoURL addObject:finalstring];
[self.MainTableView reloadData];
}
}];
}
}];
self.MainTableView.hidden = NO;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.rowitems count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
NSDictionary *stress = [self.rowitems objectAtIndex:indexPath.row];
cell.textLabel.text = stress[#"content"];
switch (indexPath.row) {
case 0:
[cell.imageView setImageWithURL:[NSURL URLWithString:[self.logoURL objectAtIndex:(0)]] placeholderImage:[UIImage imageNamed:#"greybox40.png"]];
break;
case 1:
[cell.imageView setImageWithURL:[NSURL URLWithString:[self.logoURL objectAtIndex:(1)]] placeholderImage:[UIImage imageNamed:#"greybox40.png"]];
break;
case 2:
//[cell.imageView setImageWithURL:[NSURL URLWithString:[self.logoURL objectAtIndex:(2)]] placeholderImage:[UIImage imageNamed:#"greybox40.png"]];
break;
}
return cell;
}
#end
It is erroring at CASE (1), cos it cannot see the object. any help would be brilliant, thanks.
Error at case (1) happens because you reload your table view 3 times. and every time you say to your tableView that it has 3 rows via numberOfRowsInSection: method. But in first and second iteration your self.logoURL has only 1 and then 2 objects. try this code:
if (self.logoURL.count > indexPath.row) {
[cell.imageView setImageWithURL:[NSURL URLWithString:self.logoURL[indexPath.row]] placeholderImage:[UIImage imageNamed:#"greybox40.png"]];
}
else
cell.imageView.image = nil;
also, you dont need to create NSMutableArray instance self.rowitems = [[NSMutableArray alloc] init]; because you then reassign self.rowitems property self.rowitems = [items mutableCopy];
because your for loop is override the array value and store last value only.
[array insertObject:finalString atIndex:i];
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.logoURL count];
}

My view does not update

My ParseXML method reads the value of NSNumber, which can be incremented by a click of a button.
My ParseXML method has 240 objects, each 8 have an ID from 1 to 30.
The idea is that if i increment the NSNumber from 1 to 2, it refreshes my view and grabs the 8 objects that match the ID and displays it in my view.
That is exactly what is not doing.
.h
#interface FixturesController : UITableViewController
{
NSMutableData *_responseDataFixtures;
int goUp;
NSNumber *test;
}
#property (nonatomic, retain) NSArray *tableDataFixtures;
#property (nonatomic, strong) NSMutableArray *roundParser;
#property (nonatomic, strong) NSString *seasonRoundString;
#property (nonatomic, strong) NSNumber *seasonRoundNumber;
- (IBAction)goUpByOne:(UIButton *)sender;
-(void) parseXMLFixtures:(NSNumber *) giveME;
#end
.m
- (void) viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self parseXMLFixtures:#2];
}
- (void)viewDidLoad
{
[super viewDidLoad];
goUp = 1;
test = [NSNumber numberWithInt:goUp];
}
// this allows me to increment the count of NSNumber.
- (IBAction)goUpByOne:(UIButton *)sender {
goUp++;
test = [NSNumber numberWithInt:goUp];
goUp = [test intValue];
}
-(void) parseXMLFixtures:(NSNumber *) giveME
{
giveME = test;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"There's no going back"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *xmlString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *xml = [NSDictionary dictionaryWithXMLString:xmlString];
NSMutableArray *items = [xml objectForKey:#"Match"];
NSMutableArray *newFixtureObjectArray = [[NSMutableArray alloc] init];
NSNull *nullValue = [NSNull null];
[newFixtureObjectArray insertObject:nullValue atIndex:0];
[newFixtureObjectArray insertObject:nullValue atIndex:1];
for (NSDictionary *dict in items) {
FixturesObject *myFixtures = [FixturesObject fixtureFromXMLDictionary:dict];
[newFixtureObjectArray addObject:myFixtures];
}
///////
_seasonRoundString = [NSString stringWithFormat:#"%d", [giveME intValue]];
_roundParser = [[NSMutableArray alloc]init];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"round == %#", _seasonRoundString];
NSArray *filteredArray = [newFixtureObjectArray filteredArrayUsingPredicate:predicate];
_roundParser = [NSMutableArray arrayWithArray:filteredArray];
[_roundParser insertObject:nullValue atIndex:0];
NSLog(#" Objects of Fixtures in my array %#", _roundParser);
/////
[self setTableDataFixtures:_roundParser];
}
Any suggestions? Thank you. I really need this to work so i can go sleep ˆˆ
Have you impleted the UITableViewDelegate, UITableViewDataSource methods yet?
The methods are:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{ }
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { }
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{}
You can follow this tutorial

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