Xcode Table view Data is getting duplicated when I pull to refresh - ios

Hi My data is getting duplicated every time I use the pull to refresh.. for eg. 5 initial entries in the table view are doubled to 10 with one pull to refresh and adding 5 more in the subsequent pull to refresh. How can I stop the duplication.. I would like to make sure that only new items are downloaded and existing data in the table is not downloaded again.
#implementation RootViewController
#synthesize allEntries = _allEntries;
#synthesize feeds = _feeds;
#synthesize queue = _queue;
#synthesize webViewController = _webViewController;
#pragma mark -
#pragma mark View lifecycle
- (void)addRows {
RSSEntry *entry1 = [[[RSSEntry alloc] initWithBlogTitle:#"1"
articleTitle:#"1"
articleUrl:#"1"
articleDate:[NSDate date]] autorelease];
RSSEntry *entry2 = [[[RSSEntry alloc] initWithBlogTitle:#"2"
articleTitle:#"2"
articleUrl:#"2"
articleDate:[NSDate date]] autorelease];
RSSEntry *entry3 = [[[RSSEntry alloc] initWithBlogTitle:#"3"
articleTitle:#"3"
articleUrl:#"3"
articleDate:[NSDate date]] autorelease];
[_allEntries insertObject:entry1 atIndex:0];
[_allEntries insertObject:entry2 atIndex:0];
[_allEntries insertObject:entry3 atIndex:0];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.title = #"Songs";
self.allEntries = [NSMutableArray array];
self.queue = [[[NSOperationQueue alloc] init] autorelease];
self.feeds = [NSArray arrayWithObjects:
#"http://hindisongs.bestofindia.co/?feed=rss2",
nil];
self.refreshControl = [UIRefreshControl new];
self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:#"Pull to refresh"];
[self.refreshControl addTarget:self action:#selector(bindDatas) forControlEvents:UIControlEventValueChanged];
[self bindDatas]; //called at the first time
}
-(void)bindDatas
{
//GET YOUR DATAS HEREā€¦
for (NSString *feed in _feeds) {
NSURL *url = [NSURL URLWithString:feed];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[_queue addOperation:request];
}
//update the tableView
[self.tableView reloadData];
if(self.refreshControl != nil && self.refreshControl.isRefreshing == TRUE)
{
[self.refreshControl endRefreshing];
}
}
- (void)parseRss:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
NSArray *channels = [rootElement elementsForName:#"channel"];
for (GDataXMLElement *channel in channels) {
NSString *blogTitle = [channel valueForChild:#"title"];
NSArray *items = [channel elementsForName:#"item"];
for (GDataXMLElement *item in items) {
NSString *articleTitle = [item valueForChild:#"title"];
NSString *articleUrl = [item valueForChild:#"link"];
NSString *articleDateString = [item valueForChild:#"pubDate"];
NSDate *articleDate = [NSDate dateFromInternetDateTimeString:articleDateString formatHint:DateFormatHintRFC822];
RSSEntry *entry = [[[RSSEntry alloc] initWithBlogTitle:blogTitle
articleTitle:articleTitle
articleUrl:articleUrl
articleDate:articleDate] autorelease];
[entries addObject:entry];
}
}
}
- (void)parseAtom:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
NSString *blogTitle = [rootElement valueForChild:#"title"];
NSArray *items = [rootElement elementsForName:#"entry"];
for (GDataXMLElement *item in items) {
NSString *articleTitle = [item valueForChild:#"title"];
NSString *articleUrl = nil;
NSArray *links = [item elementsForName:#"link"];
for(GDataXMLElement *link in links) {
NSString *rel = [[link attributeForName:#"rel"] stringValue];
NSString *type = [[link attributeForName:#"type"] stringValue];
if ([rel compare:#"alternate"] == NSOrderedSame &&
[type compare:#"text/html"] == NSOrderedSame) {
articleUrl = [[link attributeForName:#"href"] stringValue];
}
}
NSString *articleDateString = [item valueForChild:#"updated"];
NSDate *articleDate = [NSDate dateFromInternetDateTimeString:articleDateString formatHint:DateFormatHintRFC3339];
RSSEntry *entry = [[[RSSEntry alloc] initWithBlogTitle:blogTitle
articleTitle:articleTitle
articleUrl:articleUrl
articleDate:articleDate] autorelease];
[entries addObject:entry];
}
}
- (void)parseFeed:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
if ([rootElement.name compare:#"rss"] == NSOrderedSame) {
[self parseRss:rootElement entries:entries];
} else if ([rootElement.name compare:#"feed"] == NSOrderedSame) {
[self parseAtom:rootElement entries:entries];
} else {
NSLog(#"Unsupported root element: %#", rootElement.name);
}
}
- (void)requestFinished:(ASIHTTPRequest *)request {
[_queue addOperationWithBlock:^{
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[request responseData]
options:0 error:&error];
if (doc == nil) {
NSLog(#"Failed to parse %#", request.url);
} else {
NSMutableArray *entries = [NSMutableArray array];
[self parseFeed:doc.rootElement entries:entries];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
for (RSSEntry *entry in entries) {
int insertIdx = [_allEntries indexForInsertingObject:entry sortedUsingBlock:^(id a, id b) {
RSSEntry *entry1 = (RSSEntry *) a;
RSSEntry *entry2 = (RSSEntry *) b;
return [entry1.articleDate compare:entry2.articleDate];
}];
[_allEntries insertObject:entry atIndex:insertIdx];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:insertIdx inSection:0]]
withRowAnimation:UITableViewRowAnimationRight];
}
}];
}
}];
}
- (void)requestFailed:(ASIHTTPRequest *)request {
NSError *error = [request error];
NSLog(#"Error: %#", error);
}
/*
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
#pragma mark -
#pragma mark Table view data source
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_allEntries count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *articleDateString = [dateFormatter stringFromDate:entry.articleDate];
cell.textLabel.text = entry.articleTitle;
cell.detailTextLabel.text = [NSString stringWithFormat:#"%# - %#", articleDateString, entry.blogTitle];
return cell;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source.
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (_webViewController == nil) {
self.webViewController = [[[WebViewController alloc] initWithNibName:#"WebViewController" bundle:[NSBundle mainBundle]] autorelease];
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
_webViewController.entry = entry;
[self.navigationController pushViewController:_webViewController animated:YES];
}
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Relinquish ownership any cached data, images, etc that aren't in use.
self.webViewController = nil;
}
- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}
- (void)dealloc {
[_allEntries release];
_allEntries = nil;
[_queue release];
_queue = nil;
[_feeds release];
_feeds = nil;
[_webViewController release];
_webViewController = nil;
[super dealloc];
}

The issue is that you keep inserting object to _allEntries without ever reseting it. You will want to empty it out at some point, either when the user pulls to refresh or when the new data comes in before you add any new objects to it.
[_allEntries removeAllObjects];
Try putting it at the start of bindDatas.

Related

How to resolve when UITableview is double open on same page

I have 2 UITableView. On first UITableView make for search and select cell. After selected cell from UITableView1. It's will show blank data of UITableView2 and show new UITableView2 again with data.
I'm sorry for my bad english language.
I can speak english a little bit.
If you don't understand my question.
Please follow to see pictures below here.
First UITableView: (Click button for go to second UITableView.)
After click button. UITableView2 show blank data.
And auto show new UITableView2 with data again.
UITableView1
#interface SearchByContainerDetailViewController ()
#property (weak, nonatomic) IBOutlet UITableView *tableViewWhereHoseList;
#end
#implementation SearchByContainerDetailViewController
#synthesize labelName,strName,txResult,strResult,labelStatus;
NSString *selectedWhereHouse;
GlobalVariable *gloablOnWherehouse;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
labelName.text = strName;
//txResult.text = strResult;
labelStatus.text = #"NULL";
gloablOnWherehouse = [GlobalVariable sharedInstance];
gloablOnWherehouse.arTableDataSelectedWhereHouse = [[NSArray alloc] init];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return (gloablOnWherehouse.arTableDataSelected)?[gloablOnWherehouse.arTableDataSelected count]:1;
}
- (NSInteger) tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"%lu", (unsigned long)[gloablOnWherehouse.arTableDataSelected count]);
return (gloablOnWherehouse.arTableDataSelected)?[gloablOnWherehouse.arTableDataSelected count]:1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SearchByContainerDetailViewCell";
SearchByContainerDetailViewCell *cell = [self.tableViewWhereHoseList dequeueReusableCellWithIdentifier:simpleTableIdentifier forIndexPath:indexPath];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"SearchByContainerDetailViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
} else {
if (gloablOnWherehouse.arTableDataSelected) {
NSMutableArray *myMutbleArray = [[NSMutableArray alloc] init];
[myMutbleArray addObject:gloablOnWherehouse.arTableDataSelected];
if (myMutbleArray) {
NSDictionary *myDic = [gloablOnWherehouse.arTableDataSelected objectAtIndex:indexPath.row];
NSDictionary *cont = [myDic objectForKey:#"DataList_SPI_Detail"];
NSString *date = [self getString:[cont objectForKey:#"date"]];
NSString *qty = [self getString:[cont objectForKey:#"qty"]];
NSString *stock = [self getString:[cont objectForKey:#"stock"]];
NSString *ord = [self getString:[cont objectForKey:#"ord"]];
NSString *custmr = [self getString:[cont objectForKey:#"custmr"]];
NSString *remarks = [self getString:[cont objectForKey:#"remarks"]];
NSString *invoice = [self getString:[cont objectForKey:#"invoice"]];
NSString *due = [self getString:[cont objectForKey:#"due"]];
NSString *lot = [self getString:[cont objectForKey:#"lot"]];
NSString *gap = [self getString:[cont objectForKey:#"gap"]];
[cell setDate:date setQty:qty setStock:stock setOrd:ord setCustmr:custmr setRemarks:remarks setInvoice:invoice setDue:due setLot:lot setGap:gap];
}
}
}
return cell;
}
- (void) requestEWIServiceFinish:(EWIConnector *)connector responseData:(NSDictionary *)responseData{
NSLog(#"finish %#",connector.serviceName);
NSLog(#"response %#",responseData);
if ([connector.serviceName isEqualToString:#"special_selected_f10"])
{
NSLog(#"finish %#",connector.serviceName);
NSDictionary *content = responseData[#"content"];
NSString *stAlertMes = [content objectForKey:#"alertMessage"];
stAlertMes = [self getString:stAlertMes];
NSLog(#"AlertMSG : %#", stAlertMes);
if (![stAlertMes isEqualToString:#""]) {
NSLog(#"ALERT MESSAGE : %#", stAlertMes);
gloablOnWherehouse.arTableDataSelected = [[NSArray alloc] init];
}
else
{
NSLog(#"HAS DATA");
gloablOnWherehouse.arTableDataSelected = [content objectForKey:#"DataList_SPI_DetailCollection"];
[self.tableViewWhereHoseList reloadData];
labelStatus.text = #"F11";
}
}
else
{
NSLog(#"response %#",responseData);
}
}
- (void) requestEWIServiceFail:(EWIConnector *)connector error:(NSError *)error{
NSLog(#"request fail %#",connector);
}
- (NSString *)getString:(NSString *)string
{
return [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
- (IBAction)btnf10
{
NSMutableDictionary *content = [NSMutableDictionary dictionary];
[content setValue:[[AppSetting sharedInstance] token] forKey:#"ewitoken"];
//[content setValue:gloablOnWherehouse.selectedWhereHouse forKey:#"model_Name"];
[[EWIConnector connector] requestEWIService:#"special_selected_f10" requestData:content delegate:self];
}
UITableView2
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
globlOnDisplayEffect = [GlobalVariable sharedInstance];
globlOnDisplayEffect.arTableDataSelectedWhereHouse = [[NSArray alloc] init];
[self.tableViewDetailList reloadData];
}
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return (globlOnDisplayEffect.arTableDataSelected)?[globlOnDisplayEffect.arTableDataSelected count]: 1;
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = #"DisplayEffectQtyViewCell";
DisplayEffectQtyViewCell *cell = [self.tableViewDetailList dequeueReusableCellWithIdentifier:simpleTableIdentifier forIndexPath:indexPath];
if(cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"DisplayEffectQtyViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
} else {
if (globlOnDisplayEffect.arTableDataSelected) {
NSMutableArray *myMutbleArray = [[NSMutableArray alloc] init];
[myMutbleArray addObject:globlOnDisplayEffect.arTableDataSelected];
if (myMutbleArray) {
NSDictionary *myDic = [globlOnDisplayEffect.arTableDataSelected objectAtIndex:indexPath.row];
NSDictionary *cont = [myDic objectForKey:#"DataList_SPI_DetailF10"];
NSString *f10_cmpt = [self getString:[cont objectForKey:#"f10_cmpt"]];
NSString *f10_dt = [self getString:[cont objectForKey:#"f10_dt"]];
NSString *f10_item = [self getString:[cont objectForKey:#"f10_item"]];
NSString *f10_lot = [self getString:[cont objectForKey:#"f10_lot"]];
NSString *f10_model = [self getString:[cont objectForKey:#"f10_model"]];
NSString *f10_of = [self getString:[cont objectForKey:#"f10_of"]];
NSString *f10_semi = [self getString:[cont objectForKey:#"f10_semi"]];
NSString *f10_tm = [self getString:[cont objectForKey:#"f10_tm"]];
NSString *f10_uncmp = [self getString:[cont objectForKey:#"f10_uncmp"]];
[cell setf10_cmpt:f10_cmpt setf10_dt:f10_dt setf10_item:f10_item setf10_lot:f10_lot setf10_model:f10_model setf10_of:f10_of setf10_semi:f10_semi setf10_tm:f10_tm setf10_uncmp:f10_uncmp];
}
}
}
return cell;
}
- (void) requestEWIServiceStart:(EWIConnector *)connector{
NSLog(#"start %#",connector.endpoint);
}
TO Check if view controller already push or not.
if(![self.navigationController.topViewController isKindOfClass:[NewViewController class]]) {
[self.navigationController pushViewController:newViewController animated:YES];
}

Tableview is not showing cells in the time i posted

I have created a app that fetches information from a blog and shows it in the app. After i fetch the data it is supposed to be shown on the table view. It shows the things that i have posted but the things are in alphabetical order rather than the time i posted the thing.
Here is the code
#implementation EventsTableViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.firstLettersArray = [NSMutableArray array];
self.eventsDictionary = [NSMutableDictionary dictionary];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self searchForEvents];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[self searchForEvents];
}
- (void)searchForEvents
{
[self.searchBar resignFirstResponder];
NSString *eventsSearchUrlString = [NSString stringWithFormat:#"https://www.googleapis.com/blogger/v3/blogs/1562818803553764290/posts?key=AIzaSyBTOxz-vPHgzIkw9k88hDKd99ILTaXTt0Y"];
NSURL *eventsSearchUrl = [NSURL URLWithString:eventsSearchUrlString];
NSURLRequest *eventsSearchUrlRequest = [NSURLRequest requestWithURL:eventsSearchUrl];
NSURLSession *sharedUrlSession = [NSURLSession sharedSession];
NSURLSessionDataTask *searchEventsTask =
[sharedUrlSession dataTaskWithRequest:eventsSearchUrlRequest completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error)
{
dispatch_async(dispatch_get_main_queue(),
^{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
if(error)
{
UIAlertView *searchAlertView = [[UIAlertView alloc] initWithTitle:#"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[searchAlertView show];
}
else
{
NSString *resultString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Search results: %#", resultString);
NSError *jsonParseError = nil;
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonParseError];
if(jsonParseError)
{
UIAlertView *jsonParseErrorAlert = [[UIAlertView alloc] initWithTitle:#"Error" message:jsonParseError.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[jsonParseErrorAlert show];
}
else
{
for(NSString *key in jsonDictionary.keyEnumerator)
{
NSLog(#"First level key: %#", key);
}
[self.firstLettersArray removeAllObjects];
[self.eventsDictionary removeAllObjects];
NSArray *searchResultsArray = [jsonDictionary objectForKey:#"items"];
//NSLog(#"test%#",searchResultsArray);
for(NSDictionary *eventsInfoDictionary in searchResultsArray)
{
Events *event = [[Events alloc] init];
event.eventName = [eventsInfoDictionary objectForKey:#"title"];
event.eventDescription =[eventsInfoDictionary objectForKey:#"content"];
NSLog(#"Event Name : %#",event.eventName);
NSLog(#"Event Description : %#",event.eventDescription);
NSString *eventsFirstLetter = [event.eventName substringToIndex:1];
NSMutableArray *eventsWithFirstLetter = [self.eventsDictionary objectForKey:eventsFirstLetter];
if(!eventsWithFirstLetter)
{
eventsWithFirstLetter = [NSMutableArray array];
[self.firstLettersArray addObject:eventsFirstLetter];
}
[eventsWithFirstLetter addObject:event];
[self.eventsDictionary setObject:eventsWithFirstLetter forKey:eventsFirstLetter];
if ([event.eventDescription containsString:#"<br />"]) {
NSString* eventDescrip = event.eventDescription;
NSString* stringWithoutHTMLtags = [eventDescrip stringByReplacingOccurrencesOfString:#"<br />" withString:#""];
event.eventDescription = stringWithoutHTMLtags;
}
NSLog(#"Event Name : %#",event.eventName);
NSLog(#"Event Description : %#",event.eventDescription);
}
[self.firstLettersArray sortUsingSelector:#selector(compare:)];
[self.tableView reloadData];
}
}
});
}];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[searchEventsTask resume];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return self.firstLettersArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSString *firstLetter = [self.firstLettersArray objectAtIndex:section];
NSArray *eventsWithFirstLetter = [self.eventsDictionary objectForKey:firstLetter];
return eventsWithFirstLetter.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"eventTitleCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSString *firstLetter = [self.firstLettersArray objectAtIndex:indexPath.section];
NSArray *eventsWithFirstLetter = [self.eventsDictionary objectForKey:firstLetter];
Events *event = [eventsWithFirstLetter objectAtIndex:indexPath.row];
cell.textLabel.text = event.eventName;
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
/*
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSString *cellText = cell.textLabel.text;
NSLog(#"Row selected %#",cellText);*/
NSString *firstLetter = [self.firstLettersArray objectAtIndex:indexPath.section];
NSArray *eventsWithFirstLetter = [self.eventsDictionary objectForKey:firstLetter];
Events *event = [eventsWithFirstLetter objectAtIndex:indexPath.row];
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:#"Main" bundle: nil];
DescriptionViewController *descriptionViewController = (DescriptionViewController*)[mainStoryboard instantiateViewControllerWithIdentifier: #"descriptionController"];
descriptionViewController.eventNameDesc = event.eventDescription;
descriptionViewController.navigationItem.title = event.eventName;
[self.navigationController pushViewController:descriptionViewController animated:YES];
}
#end
You are trying to sort firstLettersArray which contain Events objects by using standard sort: function which doesn't know how to work with your custom objects.
You can use sortedArrayUsingComparator: function like this:
[firstLettersArray sortedArrayUsingComparator:^NSComparisonResult(Events *obj1, Events *obj2) {
// return object comparison result here
}];
Edit: Also you need to have NSDate property in Events class and feel it with event created time. I believe event created time should be contained in eventsInfoDictionary. Eventually you will be able to compare obj1 and obj2 using NSDate property.
i think this line not working
[self.firstLettersArray sortUsingSelector:#selector(compare:)];
use this line of code may help you....
sortedArray = [anArray sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];

UITableview cellForRowAtIndexPath method is not executing?

When i click search it executes a search class and after finding the results it executes numberOfRows method but then it is showing empty table. It is not executing cellForRowAtIndexPath method .
check my below code
code in viewcontroller.h
when i click search button this method will get executed
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
SearchResultsViewController *searchRes=[[SearchResultsViewController alloc]initWithNibName:#"SearchResultsViewController" bundle:nil];
NSString *searchQuery=[search text];
sharedManager=[Mymanager sharedManager];
sharedManager.searchQuery=searchQuery;
[searchRes searchString:searchQuery];
[self.navigationController pushViewController:searchRes animated:YES];
}
in search class
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSLog(#"%#",results);
return [results count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView1 dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.textLabel.adjustsFontSizeToFitWidth = YES;
NSLog(#"indexpath%d",indexPath.row);
NSLog(#"%#",[results objectAtIndex:[indexPath row]]);
SearchResult* hit = (SearchResult*)[results objectAtIndex:[indexPath row]];
NSLog(#"%#",hit.neighboringText);
cell.textLabel.text = [NSString stringWithFormat:#"...%#...", hit.neighboringText];
cell.detailTextLabel.text = [NSString stringWithFormat:#"Chapter %d - page %d", hit.chapterIndex, hit.pageIndex+1];
cell.textLabel.font = [UIFont fontWithName:#"Trebuchet MS" size:12];
cell.textLabel.textColor = [UIColor colorWithRed:25/255.0 green:90/255.0 blue:100/255.0 alpha:1];
// else
// {
//
// }
// [[self resultsTableView] reloadData];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
SearchResult* hit = (SearchResult*)[results objectAtIndex:[indexPath row]];
[fvc loadSpine:hit.chapterIndex atPageIndex:hit.pageIndex highlightSearchResult:hit];
}
- (void) searchString:(NSString*)query{
// if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
// {
self.results = [[NSMutableArray alloc] init];
[resultsTableView reloadData];
currentQuery=sharedManager.searchQuery;
//
[self searchString:currentQuery inChapterAtIndex:0];
//
// }else {
// currentQuery=sharedManager.searchQuery;
// [self searchString:currentQuery inChapterAtIndex:0];
//}
}
- (void) searchString:(NSString *)query inChapterAtIndex:(int)index{
currentChapterIndex = index;
sharedManager=[Mymanager sharedManager];
Chapter* chapter = [sharedManager.spineArray objectAtIndex:index];
NSLog(#"%d",chapter.text.length);
NSRange range = NSMakeRange(0, chapter.text.length);
NSLog(#"%#",sharedManager.searchQuery);
range = [chapter.text rangeOfString:sharedManager.searchQuery options:NSCaseInsensitiveSearch range:range locale:nil];
int hitCount=0;
while (range.location != NSNotFound) {
range = NSMakeRange(range.location+range.length, chapter.text.length-(range.location+range.length));
range = [chapter.text rangeOfString:sharedManager.searchQuery options:NSCaseInsensitiveSearch range:range locale:nil];
hitCount++;
}
if(hitCount!=0){
UIWebView* webView = [[UIWebView alloc] initWithFrame:chapter.windowSize];
[webView setDelegate:self];
NSURLRequest* urlRequest = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:chapter.spinePath]];
[webView loadRequest:urlRequest];
} else {
if((currentChapterIndex+1)<[sharedManager.spineArray count]){
[self searchString:sharedManager.searchQuery inChapterAtIndex:(currentChapterIndex+1)];
} else {
fvc.searching = NO;
}
}
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
NSLog(#"%#", error);
[webView release];
}
- (void) webViewDidFinishLoad:(UIWebView*)webView{
NSString *varMySheet = #"var mySheet = document.styleSheets[0];";
NSString *addCSSRule = #"function addCSSRule(selector, newRule) {"
"if (mySheet.addRule) {"
"mySheet.addRule(selector, newRule);" // For Internet Explorer
"} else {"
"ruleIndex = mySheet.cssRules.length;"
"mySheet.insertRule(selector + '{' + newRule + ';}', ruleIndex);" // For Firefox, Chrome, etc.
"}"
"}";
NSString *insertRule1 = [NSString stringWithFormat:#"addCSSRule('html', 'padding: 0px; height: %fpx; -webkit-column-gap: 0px; -webkit-column-width: %fpx;')", webView.frame.size.height, webView.frame.size.width];
NSString *insertRule2 = [NSString stringWithFormat:#"addCSSRule('p', 'text-align: justify;')"];
NSString *setTextSizeRule = [NSString stringWithFormat:#"addCSSRule('body', '-webkit-text-size-adjust: %d%%;')",[[sharedManager.spineArray objectAtIndex:currentChapterIndex] fontPercentSize]];
[webView stringByEvaluatingJavaScriptFromString:varMySheet];
[webView stringByEvaluatingJavaScriptFromString:addCSSRule];
[webView stringByEvaluatingJavaScriptFromString:insertRule1];
[webView stringByEvaluatingJavaScriptFromString:insertRule2];
[webView stringByEvaluatingJavaScriptFromString:setTextSizeRule];
[webView highlightAllOccurencesOfString:sharedManager.searchQuery];
NSString* foundHits = [webView stringByEvaluatingJavaScriptFromString:#"results"];
NSLog(#"%#", foundHits);
NSMutableArray* objects = [[NSMutableArray alloc] init];
NSArray* stringObjects = [foundHits componentsSeparatedByString:#";"];
for(int i=0; i<[stringObjects count]; i++){
NSArray* strObj = [[stringObjects objectAtIndex:i] componentsSeparatedByString:#","];
if([strObj count]==3){
[objects addObject:strObj];
}
}
NSArray* orderedRes = [objects sortedArrayUsingComparator:^(id obj1, id obj2){
int x1 = [[obj1 objectAtIndex:0] intValue];
int x2 = [[obj2 objectAtIndex:0] intValue];
int y1 = [[obj1 objectAtIndex:1] intValue];
int y2 = [[obj2 objectAtIndex:1] intValue];
if(y1<y2){
return NSOrderedAscending;
} else if(y1>y2){
return NSOrderedDescending;
} else {
if(x1<x2){
return NSOrderedAscending;
} else if (x1>x2){
return NSOrderedDescending;
} else {
return NSOrderedSame;
}
}
}];
[objects release];
NSLog(#"%#",currentQuery);
for(int i=0; i<[orderedRes count]; i++){
NSArray* currObj = [orderedRes objectAtIndex:i];
SearchResult* searchRes = [[SearchResult alloc] initWithChapterIndex:currentChapterIndex pageIndex:([[currObj objectAtIndex:1] intValue]/webView.bounds.size.height) hitIndex:0 neighboringText:[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:#"unescape('%#')", [currObj objectAtIndex:2]]] originatingQuery:currentQuery];
[results addObject:searchRes];
NSLog(#"%#",results);
[searchRes release];
}
//Print results
for(int i=0;i<[results count];i++)
{
SearchResult* hit = (SearchResult*)[results objectAtIndex:i];
NSLog(#"%#",hit.neighboringText);
}
[resultsTableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:NO];
if((currentChapterIndex+1)<[sharedManager.spineArray count]){
[self searchString:sharedManager.searchQuery inChapterAtIndex:(currentChapterIndex+1)];
} else {
fvc.searching= NO;
}
[[self resultsTableView] reloadData];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
//- (void)dealloc
////{
//// self.resultsTableView = nil;
//// //[results release];
//// //[currentQuery release];
//// [super dealloc];
//}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
resultsTableView=[[UITableView alloc]init];
[resultsTableView setDelegate:self];
[resultsTableView setDataSource:self];
sharedManager=[Mymanager sharedManager];
// Do any additional setup after loading the view from its nib.
results = [[NSMutableArray alloc] init];
self.navigationItem.title=#"Search ";
UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
initWithTitle:#"Back"
style:UIBarButtonItemStylePlain
target:nil
action:nil];
self.navigationItem.backBarButtonItem=backButton;
[[UINavigationBar appearance] setTitleTextAttributes: #{
UITextAttributeTextColor: [UIColor whiteColor],
UITextAttributeTextShadowColor: [UIColor lightGrayColor],
UITextAttributeTextShadowOffset: [NSValue valueWithUIOffset:UIOffsetMake(0.0f, 1.0f)],
UITextAttributeFont: [UIFont fontWithName:#"Trebuchet MS" size:15.0f]
}];
noMatchingSearch=[[NSArray alloc]initWithObjects:#"No Element Found", nil];
tableOfContents=[[NSMutableArray alloc]init];
for (id img in search.subviews)
{
if ([img isKindOfClass:NSClassFromString(#"UISearchBarBackground")])
{
[img removeFromSuperview];
}
}
tableOfContents=[sharedManager.List copy];
}
- (void)viewDidUnload
{
search = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
self.resultsTableView = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
MY SEARCH RESULTS
"<SearchResult: 0x113482c0>",
"<SearchResult: 0x11348a20>",
"<SearchResult: 0x88c0a50>"
The problem is with the search method before search the array is reinitialised and hence 0 returned in the resultArray and hence no value in tables
- (void) searchString:(NSString*)query{
self.results = [[NSMutableArray alloc] init];//Here it becomes 0!!
[resultsTableView reloadData];
currentQuery=sharedManager.searchQuery;
}
To make it right ,After the search is performed i believe
[self searchString:currentQuery inChapterAtIndex:0];
load the value in the result array and then reload table.
Make sure
in .h add
<UITableViewDataSource,UITableViewDelegate>
in nib
connect datasource and delegate[if via nib]

Kal datasource delegates

I'm usin Kal https://github.com/klazuka/Kal to implement a calendar. I'm using storyboard, so I add KalViewController as a child to the container view controller.
kal.delegate = self;
kal.dataSource = dataSource;
dataSource = [[CalendarDataSourceDelegate alloc] init];
kal = [[KalViewController alloc] init];
[self addChildViewController:kal];
[kal didMoveToParentViewController:self];
[self.calendarioView addSubview:kal.view];
[clickEvent insertPrintAdd:zona_competicion];
I use an external object as datasource delegate, but after fetching data from my backend by webservice, I don't know how to call delegates to load calendar with fetched data:
#implementation CalendarDataSourceDelegate
- (id)init
{
if ((self = [super init])) {
items = [[NSMutableArray alloc] init];
matches = [[NSMutableArray alloc] init];
buffer = [[NSMutableData alloc] init];
}
[self fetchHolidays];
return self;
}
- (eventMatch *)eventAtIndexPath:(NSIndexPath *)indexPath
{
return [items objectAtIndex:indexPath.row];
}
#pragma mark UITableViewDataSource protocol conformance
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = #"MyCell";
eventNoAddedCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell) {
cell = [[eventNoAddedCell alloc] initWithStyle:UITableViewCellSelectionStyleNone reuseIdentifier:identifier];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.imageView.contentMode = UIViewContentModeScaleAspectFill;
}
eventMatch *event = [self eventAtIndexPath:indexPath];
cell.escudoLocal.image = [UIImage imageNamed:[NSString stringWithFormat:#"%#.png",event.equipoLocal ]];
cell.escudoVis.image = [UIImage imageNamed:[NSString stringWithFormat:#"%#.png",event.equipoVisitante ]];
cell.equipoLocal.text = event.equipoLocal;
cell.equipoVisitante.text = event.equipoVisitante;
cell.competicion.text = event.competicion;
cell.jornada.text = event.jornada;
cell.hora.text = event.hora;
cell.canalesTV.text = event.canalesTV;
[self fetchHolidays];
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [items count];
}
#pragma mark Fetch from the internet
- (void)fetchHolidays
{
NSString *urlStr = [NSString stringWithFormat:#"http://backend.exular.net/contenido/webservices/xlr_ws_calendario.php?idp=105"];
dataReady = NO;
[matches removeAllObjects];
conn = [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]] delegate:self];
[conn start];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[buffer setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[buffer appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error=nil;
NSDictionary *tempDic = [NSJSONSerialization JSONObjectWithData:buffer options:kNilOptions error:&error];
NSArray *array = [tempDic valueForKey:#"nodes"];
NSDateFormatter *fmt = [[NSDateFormatter alloc] init] ;
[fmt setDateFormat:#"dd/MM/yyyy"];
for (NSDictionary *jornada in array) {
NSDate *d = [fmt dateFromString:[jornada objectForKey:#"fecha"]];
[matches addObject:[eventMatch equipoVisitante:[jornada valueForKey:#"id_visitante"] equipoLocal:[jornada valueForKey:#"id_local"] resultadoVisitante:[jornada valueForKey:#"res_visitante"] resultadoLocal:[jornada valueForKey:#"res_local"] canalesTV:[jornada valueForKey:#"cadenas"] date:d time:[jornada valueForKey:#"hora"] jornada:[jornada valueForKey:#"jornada"] competicion:[jornada valueForKey:#"competicion"]]]; }
dataReady = YES;
[callback loadedDataSource:self];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"HolidaysCalendarDataSource connection failure: %#", error);
}
#pragma mark KalDataSource protocol conformance
- (void)presentingDatesFrom:(NSDate *)fromDate to:(NSDate *)toDate delegate:(id<KalDataSourceCallbacks>)delegate
{
/*
* In this example, I load the entire dataset in one HTTP request, so the date range that is
* being presented is irrelevant. So all I need to do is make sure that the data is loaded
* the first time and that I always issue the callback to complete the asynchronous request
* (even in the trivial case where we are responding synchronously).
*/
if (dataReady) {
[callback loadedDataSource:self];
return;
}
callback = delegate;
[self fetchHolidays];
}
- (NSArray *)markedDatesFrom:(NSDate *)fromDate to:(NSDate *)toDate
{
if (!dataReady)
return [NSArray array];
return [[self matchesFrom:fromDate to:toDate] valueForKeyPath:#"date"];
}
- (void)loadItemsFromDate:(NSDate *)fromDate toDate:(NSDate *)toDate
{
if (!dataReady)
return;
[items addObjectsFromArray:[self matchesFrom:fromDate to:toDate]];
}
- (void)removeAllItems
{
[items removeAllObjects];
}
#pragma mark -
- (NSArray *)matchesFrom:(NSDate *)fromDate to:(NSDate *)toDate
{
NSMutableArray *matchesUpdate = [NSMutableArray array];
for (eventMatch *match in matches)
if (IsDateBetweenInclusive(match.date, fromDate, toDate))
[matchesUpdate addObject:match];
return matches;
}
- (void)dealloc
{
matches=nil;
}
First, I find strange that you alloc your KalViewController after using it, I would do it just in the opposite order:
kal = [[KalViewController alloc] init];
kal.delegate = self;
kal.dataSource = dataSource;
And then why don't you just call?:
[kal reloadData];

Add only SOME items from XML to TableView

Using this tutorial, I made an iPhone blog app. It uses the count of the array created to setup the number of rows. I don't want to do every single item, because there are over 200 right now and growing. When I return any number for rows in section, it always crashes with the error about 0 beyond bounds of empty array. What else do I need to tweak from this tutorial to only allow the first 20 items to show in tableview?
UPDATE: I think I am making some progress. In the reqeustFinished method where it sorts the array, I edited it to make it this:
NSMutableArray *entries = [NSMutableArray array];
[self parseFeed:doc.rootElement entries:entries];
[entries removeLastObject];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
for (RSSEntry *entry in entries) {
int insertIdx = [_allEntries indexForInsertingObject:entry sortedUsingBlock:^(id a, id b) {
RSSEntry *entry1 = (RSSEntry *) a;
RSSEntry *entry2 = (RSSEntry *) b;
return [entry1.articleDate compare:entry2.articleDate];
}];
NSLog(#"%#", entries);
[_allEntries insertObject:entry atIndex:insertIdx];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:insertIdx inSection:0]]
withRowAnimation:UITableViewRowAnimationRight];
Adding the line to removeLastObject for entries, removed the first item (which is ideally the ONLY one I would want on the first day). Are there other methods that would allow me to remove a range of objects at Index?
Here is the code I have for the Table View Class and DataSources.
- (void)refresh {
self.allEntries = [NSMutableArray array];
self.queue = [[[NSOperationQueue alloc] init] autorelease];
self.feeds = [NSArray arrayWithObjects:#"addressofxmlfile",
nil];
for (NSString *feed in _feeds) {
NSURL *url = [NSURL URLWithString:feed];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[_queue addOperation:request];
}
}
- (void)viewDidLoad {
[super viewDidLoad];
self.refreshControl = [[UIRefreshControl alloc] init];
[self.refreshControl addTarget:self action:#selector(refreshInvoked:forState:) forControlEvents:UIControlEventValueChanged];
[self refresh];
}
-(void) refreshInvoked:(id)sender forState:(UIControlState)state {
// Refresh table here...
[_allEntries removeAllObjects];
[self.tableView reloadData];
[self refresh];
}
- (void)parseRss:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
NSArray *channels = [rootElement elementsForName:#"channel"];
for (GDataXMLElement *channel in channels) {
NSString *blogTitle = [channel valueForChild:#"title"];
NSArray *items = [channel elementsForName:#"item"];
for (GDataXMLElement *item in items) {
NSString *articleTitle = [item valueForChild:#"title"];
NSString *articleUrl = [item valueForChild:#"guid"];
NSString *articleDateString = [item valueForChild:#"pubdate"];
NSDate *articleDate = [NSDate dateFromInternetDateTimeString:articleDateString formatHint:DateFormatHintRFC822];
NSString *articleImage = [item valueForChild:#"description"];
NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *dateofarticle = [dateFormatter stringFromDate:articleDate];
NSString *days = [articleImage substringFromIndex:7];
RSSEntry *entry = [[[RSSEntry alloc] initWithBlogTitle:blogTitle
articleTitle:articleTitle
articleUrl:articleUrl
articleDate:articleDate
articleImage:articleImage
date:thedate] autorelease];
[entries addObject:entry];
}
}
}
- (void)parseFeed:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
if ([rootElement.name compare:#"rss"] == NSOrderedSame) {
[self parseRss:rootElement entries:entries];
}else {
NSLog(#"Unsupported root element: %#", rootElement.name);
}
}
- (void)requestFinished:(ASIHTTPRequest *)request {
[_queue addOperationWithBlock:^{
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[request responseData]
options:0 error:&error];
if (doc == nil) {
NSLog(#"Failed to parse %#", request.url);
} else {
NSMutableArray *entries = [NSMutableArray array];
[self parseFeed:doc.rootElement entries:entries];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
for (RSSEntry *entry in entries) {
int insertIdx = [_allEntries indexForInsertingObject:entry sortedUsingBlock:^(id a, id b) {
RSSEntry *entry1 = (RSSEntry *) a;
RSSEntry *entry2 = (RSSEntry *) b;
return [entry1.articleDate compare:entry2.articleDate];
}];
[_allEntries insertObject:entry atIndex:insertIdx];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:insertIdx inSection:0]]
withRowAnimation:UITableViewRowAnimationRight];
}
}];
}
}];
[self.refreshControl endRefreshing];
}
- (void)requestFailed:(ASIHTTPRequest *)request {
NSError *error = [request error];
NSLog(#"Error: %#", error);
[self refresh];
}
#pragma mark -
#pragma mark Table view data source
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// [tableView setBackgroundColor:[UIColor redColor]];
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_allEntries count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
Cell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[Cell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
CALayer * l = [cell.imageView layer];
[l setMasksToBounds:YES];
[l setCornerRadius:11];
[l setBorderWidth:2.0];
[l setBorderColor:[[UIColor blackColor] CGColor]];
NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
NSString *articleDateString = [dateFormatter stringFromDate:entry.articleDate];
UIFont *cellFont = [UIFont fontWithName:#"Papyrus" size:19];
UIFont *cellFont2 = [UIFont fontWithName:#"Papyrus" size:17];
// cell.imageView.image = [UIImage imageNamed:#"icon#2x.png"];
cell.textLabel.text = entry.date;
cell.detailTextLabel.text = entry.articleTitle;
cell.detailTextLabel.textColor = [UIColor blackColor];
cell.textLabel.font = cellFont;
cell.detailTextLabel.font = cellFont2;
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 73.4;
}
You are assigning allEntries to new Array in the Refresh method here:
- (void)refresh {
self.allEntries = [NSMutableArray array];
The tutorial only does this in the ViewDidLoad Method. Not sure if this is a problem as i don't know exactly when/how refresh is called.
Found this answer that shows how to hide cells/rows here.

Resources