UITableview Delegate methods are not executing - ios

i tried the following code for searching in epub ,Its not working the reason is
1.The table delegate methode executing at startup so the default value of search results is 0 ,so i give one dummy array with 4 elements in viewdidload method.So now tableview displaying only 4 thode elements in dummy array and when i scroll the tableview it displaying correct search results but still it showing only 4 elemets in that search results because number of rows methode is not execute while scrolling.
when i click search button it will call this methode in first class
SearchResultsViewController *searchRes=[[SearchResultsViewController alloc]initWithNibName:#"SearchResultsViewController" bundle:nil];
NSString *searchQuery=[search text];
sharedManager=[Mymanager sharedManager];
sharedManager.searchQuery=searchQuery;
// UITextField *textField = [NSString stringWithFormat:#"%#",searchQuery];
// [textField setFont:[UIFont fontWithName:#"BL-Ruthika-Bold" size:15]];
[searchRes searchString:searchQuery];
[self.navigationController pushViewController:searchRes animated:YES];
then it calls following methods in searchresult class
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSLog(#"%d",[results count]);
if([results count]>0)
{
return [results count];
}
else
{
return [test count];
}
}
//executes only at the startup time ,so the value of results always become zero
- (UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
if([results count]>0) {
// cell.textLabel.adjustsFontSizeToFitWidth = YES;
hit = (SearchResult*)[results objectAtIndex:[indexPath row]];
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:13];
cell.textLabel.textColor = [UIColor colorWithRed:25/255.0 green:90/255.0 blue:100/255.0 alpha:1];
cell.detailTextLabel.textColor=[UIColor colorWithRed:25/255.0 green:90/255.0 blue:100/255.0 alpha:1];
cell.detailTextLabel.font= [UIFont fontWithName:#"Trebuchet MS" size:10];
return cell;
}
else
{
cell.textLabel.text=[test objectAtIndex:indexPath.row];
return cell;
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
sharedManager=[Mymanager sharedManager];
hit = (SearchResult*)[results objectAtIndex:[indexPath row]];
sharedManager.searchFlag=YES;
sharedManager.hitPageNumber=hit.pageIndex;
sharedManager.hitChapter=hit.chapterIndex;
sharedManager.hit=hit;
// [fvc loadSpine:hit.chapterIndex atPageIndex:hit.pageIndex highlightSearchResult:hit];
[self.navigationController popViewControllerAnimated:YES];
}
- (void) searchString:(NSString*)query{
currentQuery=sharedManager.searchQuery;
[self searchString:currentQuery inChapterAtIndex:0];
[[self resultsTableView]reloadData];
}
- (void) searchString:(NSString *)query inChapterAtIndex:(int)index{
currentChapterIndex = index;
sharedManager=[Mymanager sharedManager];
Chapter* chapter = [sharedManager.spineArray objectAtIndex:index];
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;
}
}
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
// NSLog(#"%#", error);
[webView release];
}
- (void) webViewDidFinishLoad:(UIWebView*)webView{
sharedManager=[Mymanager sharedManager];
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];
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:sharedManager.searchQuery];
[results addObject:searchRes];
[searchRes release];
}
[[self resultsTableView]reloadData];
//Print results
for(int i=0;i<[results count];i++)
{
hit = (SearchResult*)[results objectAtIndex:i];
}
[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)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];
test=[[NSArray alloc]initWithObjects:#"one",#"one",#"one",#"one",nil];
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]
}];
[self searchString:sharedManager.searchQuery];
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];
resultsTableView.delegate=self;
resultsTableView.dataSource=self;
// Release any retained subviews of the main view.
self.resultsTableView = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

When you have received your search results call
[self.tableView reloadData];
To tell the table view to update itself. I can see you have tried it a number of times in the large amount of code above. You only need to call it once, when you have your search results ready. Also, ensure your reference to the table view is valid when you call it.
Also, if you're creating a table view in an XIB file, then the second one you're creating in viewDidLoad and not showing (adding as a subview) is just confusing you and you're trying to reload the wrong table view.
If you still have problems, show the class properties and remove all the code tat isn't to do with the table view.

resultsTableView=[[UITableView alloc]init];
Try to use resultsTableView, with a property, and set it's to (nonatomic, strong).

Related

UIButton in Custom TableViewCell not Changing Value when Selecting

Thanks to #jsetting32 I have a custom UITableViewCell complete with buttons at the bottom of the tableView. However, when I am clicking those buttons, the value for the selectedState is not changing, making it a bit difficult for the end-user to tell if they have clicked it or not.
self.likeButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.likeButton addTarget:self action:#selector(didTapLikeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
[self.likeButton setTitle:#"Pray" forState:UIControlStateNormal];
[self.likeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.likeButton setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];
[[self.likeButton titleLabel] setFont:[UIFont fontWithName:#"Verdana" size:12.0f]];
[self.cellView addSubview:self.likeButton];
Try UIControlStateHighlighted instead of UIControlStateSelected
[self.likeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.likeButton setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted];
So heres how I solve the button issue... There should already be a method within your custom cell that sets the like status... It is set like so
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"cellIdentifier";
if (indexPath.row == [self.objects count])
return [self tableView:tableView cellForNextPageAtIndexPath:indexPath];
PHChatCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[PHChatCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
[cell setDelegate:self];
}
[self setCellAttributesWithCell:cell withObject:[self.object objectAtIndex:indexPath.row] withIndexPath:indexPath];
return cell;
}
- (void)setCellAttributesWithCell:(PHChatCell *)cell withObject:(PFObject *)object withIndexPath:(NSIndexPath *)indexPath
{
if (object) {
[cell setChat:object];
[cell setTag:indexPath.row];
[cell.likeButton setTag:indexPath.row];
if ([[PHCache sharedCache] attributesForMessage:object]) {
[cell setLikeStatus:[[PHCache sharedCache] isMessageLikedByCurrentUser:object]];
NSString *likeCount = [[[PHCache sharedCache] likeCountForMessage:object] description];
cell.likeCount.text = ([likeCount isEqualToString:#"1"]) ?
[NSString stringWithFormat:#"%# like", likeCount] :
[NSString stringWithFormat:#"%# likes", likeCount];
NSString *commentCount = [[[PHCache sharedCache] commentCountForMessage:object] description];
cell.commentCount.text = ([commentCount isEqualToString:#"1"]) ?
[NSString stringWithFormat:#"%# comment", commentCount] :
[NSString stringWithFormat:#"%# comments", commentCount];
return;
}
#synchronized(self) {
// Put this in your init method
// self.outstandingSectionHeadersQueries = [NSMutableDictionary dictionary]
if (![self.outstandingSectionHeaderQueries objectForKey:#(indexPath.row)]) {
PFQuery *query = [PHUtility queryForActivitiesOnMessage:object cachePolicy:kPFCachePolicyNetworkOnly];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
#synchronized(self) {
[self.outstandingSectionHeaderQueries removeObjectForKey:#(indexPath.row)];
if (error) return;
NSMutableArray *likers = [NSMutableArray array];
NSMutableArray *commenters = [NSMutableArray array];
BOOL isLikedByCurrentUser = NO;
for (PFObject *activity in objects) {
if ([[activity objectForKey:kPHActivityTypeKey] isEqualToString:kPHActivityTypeLike] && [activity objectForKey:kPHActivityFromUserKey]) {
[likers addObject:[activity objectForKey:kPHActivityFromUserKey]];
} else if ([[activity objectForKey:kPHActivityTypeKey] isEqualToString:kPHActivityTypeComment] && [activity objectForKey:kPHActivityFromUserKey]) {
[commenters addObject:[activity objectForKey:kPHActivityFromUserKey]];
}
if ([[[activity objectForKey:kPHActivityFromUserKey] objectId] isEqualToString:[[PFUser currentUser] objectId]] &&
[[activity objectForKey:kPHActivityTypeKey] isEqualToString:kPHActivityTypeLike]) {
isLikedByCurrentUser = YES;
}
}
[[PHCache sharedCache] setAttributesForMessage:object likers:likers commenters:commenters likedByCurrentUser:isLikedByCurrentUser];
if (cell.tag != indexPath.row) return;
[cell setLikeStatus:[[PHCache sharedCache] isMessageLikedByCurrentUser:object]];
NSString *likeCount = [[[PHCache sharedCache] likeCountForMessage:object] description];
cell.likeCount.text = ([likeCount isEqualToString:#"1"]) ?
[NSString stringWithFormat:#"%# like", likeCount] : [NSString stringWithFormat:#"%# likes", likeCount];
NSString *commentCount = [[[PHCache sharedCache] commentCountForMessage:object] description];
cell.commentCount.text = ([commentCount isEqualToString:#"1"]) ?
[NSString stringWithFormat:#"%# comment", commentCount] : [NSString stringWithFormat:#"%# comments", commentCount];
}
}];
}
}
}
}
- (void)PHChatCell:(PHChatCell *)cell didTapLikeButton:(UIButton *)button chat:(PFObject *)chat
{
// Disable the button so users cannot send duplicate requests
[cell shouldEnableLikeButton:NO];
//These are private interface properties to handle when the user wants to unlike the prayer
//when the UIActionsheet is loaded
self.chat = chat;
self.likeButton = button;
self.cell = cell;
if (button.selected) {
[[[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:#"Unlike" otherButtonTitles:nil] showInView:self.view];
return;
}
BOOL liked = !button.selected;
[cell setLikeStatus:liked];
NSString *originalButtonTitle = button.titleLabel.text;
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"]];
NSNumber *likeCount = [numberFormatter numberFromString:button.titleLabel.text];
[button setTitle:#"Liked" forState:UIControlStateNormal];
[UIView animateWithDuration:0.25 animations:^{
[cell.likeImage setImage:[UIImage imageNamed:#"ButtonLikeSelected.png"]];
[cell.likeImage setTransform:CGAffineTransformMakeScale(1.5, 1.5)];
} completion:^(BOOL finished){
[UIView animateWithDuration:0.25 animations:^{
[cell.likeImage setTransform:CGAffineTransformMakeScale(1, 1)];
}];
}];
NSInteger checker = [[cell.likeCount text] integerValue] + 1;
cell.likeCount.text = (checker == 1) ?
[NSString stringWithFormat:#"%ld like", (long)checker] :
[NSString stringWithFormat:#"%ld likes", (long)checker];
likeCount = [NSNumber numberWithInt:[likeCount intValue] + 1];
[[PHCache sharedCache] incrementLikerCountForMessage:chat];
[[PHCache sharedCache] setMessageIsLikedByCurrentUser:chat liked:liked];
[PHUtility likeMessageInBackground:chat block:^(BOOL succeeded, NSError *error) {
PHChatCell *actualCell = (PHChatCell *)[self tableView:self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:button.tag inSection:0]];
[actualCell shouldEnableLikeButton:YES];
[actualCell setLikeStatus:succeeded];
if (!succeeded) {
[actualCell.likeButton setTitle:originalButtonTitle forState:UIControlStateNormal];
}
}];
}
#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0) {
BOOL liked = !self.likeButton.selected;
[self.cell setLikeStatus:liked];
[self.likeButton setTitle:#"Like" forState:UIControlStateNormal];
[self.cell.likeImage setImage:[UIImage imageNamed:#"ButtonLike.png"]];
NSInteger checker = [[self.cell.likeCount text] integerValue] - 1;
self.cell.likeCount.text = (checker == 1) ?
[NSString stringWithFormat:#"%ld like", (long)checker] :
[NSString stringWithFormat:#"%ld likes", (long)checker];
NSString *originalButtonTitle = self.likeButton.titleLabel.text;
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
NSNumber *likeCount = [numberFormatter numberFromString:self.likeButton.titleLabel.text];
likeCount = [NSNumber numberWithInt:[likeCount intValue] + 1];
if ([likeCount intValue] > 0) {
likeCount = [NSNumber numberWithInt:[likeCount intValue] - 1];
}
[[PHCache sharedCache] decrementLikerCountForMessage:self.chat];
[[PHCache sharedCache] setMessageIsLikedByCurrentUser:self.chat liked:NO];
[PHUtility unlikeMessageInBackground:self.chat block:^(BOOL succeeded, NSError *error) {
PHChatCell *actualCell = (PHChatCell *)[self tableView:self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.likeButton.tag inSection:0]];
[actualCell shouldEnableLikeButton:YES];
[actualCell setLikeStatus:!succeeded];
if (!succeeded) {
[actualCell.likeButton setTitle:originalButtonTitle forState:UIControlStateNormal];
}
}];
}
}
Here is the query method used in the previous snippet of code (declared in PHUtility class) :
+ (PFQuery *)queryForActivitiesOnMessage:(PFObject *)message cachePolicy:(PFCachePolicy)cachePolicy {
PFQuery *queryLikes = [PFQuery queryWithClassName:kPHActivityClassKey];
[queryLikes whereKey:kPHActivityMessageKey equalTo:message];
[queryLikes whereKey:kPHActivityTypeKey equalTo:kPHActivityTypeLike];
PFQuery *queryComments = [PFQuery queryWithClassName:kPHActivityClassKey];
[queryComments whereKey:kPHActivityMessageKey equalTo:message];
[queryComments whereKey:kPHActivityTypeKey equalTo:kPHActivityTypeComment];
PFQuery *query = [PFQuery orQueryWithSubqueries:[NSArray arrayWithObjects:queryLikes,queryComments,nil]];
[query setCachePolicy:cachePolicy];
[query includeKey:kPHActivityFromUserKey];
[query includeKey:kPHActivityMessageKey];
return query;
}
Here are the PHCache implementation ...
#interface PHCache()
#property (nonatomic, strong) NSCache *cache;
- (void)setAttributes:(NSDictionary *)attributes forMessage:(PFObject *)message;
#end
#implementation PHCache
#synthesize cache;
#pragma mark - Initialization
+ (id)sharedCache {
static dispatch_once_t pred = 0;
__strong static id _sharedObject = nil;
dispatch_once(&pred, ^{
_sharedObject = [[self alloc] init];
});
return _sharedObject;
}
- (id)init {
self = [super init];
if (self) {
self.cache = [[NSCache alloc] init];
}
return self;
}
- (void)clear {
[self.cache removeAllObjects];
}
- (void)setAttributes:(NSDictionary *)attributes forMessage:(PFObject *)message {
[self.cache setObject:attributes forKey:[self keyForMessage:message]];
}
- (NSString *)keyForMessage:(PFObject *)message {
return [NSString stringWithFormat:#"message_%#", [message objectId]];
}
#pragma mark - Global Chat
- (void)setAttributesForMessage:(PFObject *)message
likers:(NSArray *)likers
commenters:(NSArray *)commenters
likedByCurrentUser:(BOOL)likedByCurrentUser {
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:likedByCurrentUser],kPHMessageAttributesIsLikedByCurrentUserKey,
#([likers count]),kPHMessageAttributesLikeCountKey,
likers,kPHMessageAttributesLikersKey,
#([commenters count]),kPHMessageAttributesCommentCountKey,
commenters,kPHMessageAttributesCommentersKey,
nil];
[self setAttributes:attributes forMessage:message];
}
- (NSDictionary *)attributesForMessage:(PFObject *)message {
return [self.cache objectForKey:[self keyForMessage:message]];
}
- (NSNumber *)likeCountForMessage:(PFObject *)message {
NSDictionary *attributes = [self attributesForMessage:message];
if (attributes) {
return [attributes objectForKey:kPHMessageAttributesLikeCountKey];
}
return [NSNumber numberWithInt:0];
}
- (NSNumber *)commentCountForMessage:(PFObject *)message {
NSDictionary *attributes = [self attributesForMessage:message];
if (attributes) {
return [attributes objectForKey:kPHMessageAttributesCommentCountKey];
}
return [NSNumber numberWithInt:0];
}
- (NSArray *)likersForMessage:(PFObject *)message {
NSDictionary *attributes = [self attributesForMessage:message];
if (attributes) {
return [attributes objectForKey:kPHMessageAttributesLikersKey];
}
return [NSArray array];
}
- (NSArray *)commentersForMessage:(PFObject *)message {
NSDictionary *attributes = [self attributesForMessage:message];
if (attributes) {
return [attributes objectForKey:kPHMessageAttributesCommentersKey];
}
return [NSArray array];
}
- (void)setMessageIsLikedByCurrentUser:(PFObject *)message liked:(BOOL)liked {
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:[self attributesForMessage:message]];
[attributes setObject:[NSNumber numberWithBool:liked] forKey:kPHMessageAttributesIsLikedByCurrentUserKey];
[self setAttributes:attributes forMessage:message];
}
- (BOOL)isMessageLikedByCurrentUser:(PFObject *)message {
NSDictionary *attributes = [self attributesForMessage:message];
if (attributes) {
return [[attributes objectForKey:kPHMessageAttributesIsLikedByCurrentUserKey] boolValue];
}
return NO;
}
- (void)incrementLikerCountForMessage:(PFObject *)message {
NSNumber *likerCount = [NSNumber numberWithInt:[[self likeCountForMessage:message] intValue] + 1];
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:[self attributesForMessage:message]];
[attributes setObject:likerCount forKey:kPHMessageAttributesLikeCountKey];
[self setAttributes:attributes forMessage:message];
}
- (void)decrementLikerCountForMessage:(PFObject *)message {
NSNumber *likerCount = [NSNumber numberWithInt:[[self likeCountForMessage:message] intValue] - 1];
if ([likerCount intValue] < 0) {
return;
}
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:[self attributesForMessage:message]];
[attributes setObject:likerCount forKey:kPHMessageAttributesLikeCountKey];
[self setAttributes:attributes forMessage:message];
}
- (void)incrementCommentCountForMessage:(PFObject *)message {
NSNumber *commentCount = [NSNumber numberWithInt:[[self commentCountForMessage:message] intValue] + 1];
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:[self attributesForMessage:message]];
[attributes setObject:commentCount forKey:kPHMessageAttributesCommentCountKey];
[self setAttributes:attributes forMessage:message];
}
- (void)decrementCommentCountForMessage:(PFObject *)message {
NSNumber *commentCount = [NSNumber numberWithInt:[[self commentCountForMessage:message] intValue] - 1];
if ([commentCount intValue] < 0) {
return;
}
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:[self attributesForMessage:message]];
[attributes setObject:commentCount forKey:kPHMessageAttributesCommentCountKey];
[self setAttributes:attributes forMessage:message];
}
- (NSNumber *)messageCountForUser:(PFUser *)user {
NSDictionary *attributes = [self attributesForUser:user];
if (attributes) {
NSNumber *photoCount = [attributes objectForKey:kPHUserAttributesMessageCountKey];
if (photoCount) {
return photoCount;
}
}
return [NSNumber numberWithInt:0];
}
- (void)setMessageCount:(NSNumber *)count user:(PFUser *)user {
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:[self attributesForUser:user]];
[attributes setObject:count forKey:kPHUserAttributesMessageCountKey];
[self setAttributes:attributes forUser:user];
}
Like I said in your previous post... It requires a hefty amount of code to make this feature 'optimal'... Reason for the cache object is to limit api requests to the servers. If the cell has been loaded, we're gonna check the cache to see if the attributes for the cell have been loaded, if it hasn't query to the server to get the attributes and set the cache to ensure we don't need to make an api request in the future...
All the variables starting with kPH are constants that you can declare on your own, or how you feel is sufficient... Like I said before, checking out the Anypic project and integrating the features into your app is best. Just copy over the PAPCache class and PAPUtility class over. Just make sure you read over the code to fully understand what is going on to get a better sense of how to integrate the code with yours, and to extend it to add more features to your app.
If you have any issues please feel free to post a comment.
i. While touching use UIControlStateHighlighted as suggested above.
ii. Keep a different color:
Since you have a custom UITableViewCell, you should implement an IBAction and set your UIButton to this using
[self.likeButton addTarget:self action:#selector(select:) forControlEvents:UIControlEventTouchUpInside];
in the .m file of your cell set:
-(IBAction)onSelectCellClicked:(id)sender {
if(self.yourButton.selected) {
self.yourButton.selected = NO;
} else {
self.yourButton.selected = YES;
}
}
Now set the cell's delegate to self in cell for row after putting this in the cell's .h file:
#protocol CustomCellDelegate <NSObject>
#end
#interface CustomCell : UITableViewCell
#property (strong, nonatomic) NSObject<CustomCellDelegate>* delegate;
#end
And put in the VC that is presenting the UITableView using the custom cell.
you can just add this line into 'didTapLikeButtonAction' :
self.likeButton.selected = !self.likeButton.selected;
once you change the selected state, the button will change its title color.
you may also want to add this line for a smoother effect:
[self.likeButton setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted];

Updating UILabel and Deleteing row from UItableview

I have a UITableview and I populate the rows with data from an api.
I have made code to update the label of the item in the cell row if more than on of the same item is added to the tableview. If a new item is added it populates a new cell row with the information.
I am trying now to use the UITableview editing method to delete rows from the UITableview.
I have no problem with deleting rows but My problem is that how can I delete the quantity if the item in the cell row is more than 1 and if the quantuty is only one delete the cell row.
I am getting a strange bug when trying to do this.
My code minuses to many times, please see my code and screenshots.
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
NSLog(#"Order ID: %ld", (long)self.orderId);
if ([self.prevVC isKindOfClass:[MyOrdersViewController class]]) {
NSLog(#"from my orders view");
[self.tableView reloadData];
}else {
NSLog(#"from my deli item view %#", self.deli.deliId);
NSLog(#"from my menu item view %ld", (long)self.menuItem.menuItemId);
NSLog(#"menu item array %#", self.menuItem);
self.viewOrderSummaryDictionary = [[NSMutableDictionary alloc] init];
[self.viewOrderSummaryDictionary setObject: [NSNumber numberWithInteger: self.menuItem.menuItemId] forKey: #"id"];
[self.viewOrderSummaryDictionary setObject: self.menuItem.menuItemDescription forKey: #"description"];
[self.viewOrderSummaryDictionary setObject: self.menuItem.menuItemImageURL forKey: #"imageUrlString"];
[self.viewOrderSummaryDictionary setObject: self.menuItem.menuItemPrice forKey: #"price"];
[self.viewOrderSummaryDictionary setObject: self.menuItem.menuItemCurrency forKey: #"currency"];
NSArray *arr = [self.newestViewOrderSummaryArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"id == %#", [NSNumber numberWithInteger: self.menuItem.menuItemId]]];
NSLog(#"arr arr arr %#", arr);
if (arr && arr.count == 1) {
NSMutableDictionary* foundMenuItem = (NSMutableDictionary*) [arr objectAtIndex: 0];
self.quantity = [[foundMenuItem objectForKey: #"quantity"] intValue];
self.quantity++;
[foundMenuItem setObject: [NSString stringWithFormat: #"%d", self.quantity] forKey: #"quantity"];
[self.newestViewOrderSummaryArray removeObject: foundMenuItem];
self.viewOrderSummaryArray = [[NSMutableArray alloc] initWithArray: self.newestViewOrderSummaryArray];
[self.viewOrderSummaryArray addObject: foundMenuItem];
}
else {
[self.viewOrderSummaryDictionary setObject: #"1" forKey: #"quantity"];
[self.viewOrderSummaryArray addObject: self.viewOrderSummaryDictionary];
[self.viewOrderSummaryArray addObjectsFromArray: self.newestViewOrderSummaryArray];
}
[self.tableView reloadData];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
[self showBackButton];
self.navBarBackLabel = [[UILabel alloc] initWithFrame: CGRectMake(65, 5, 200, 30)];
self.title = NSLocalizedString(#"View Order Summary", nil);
self.navBarBackLabel.textColor = [UIColor appRedColor];
self.navBarBackLabel.font = [UIFont fontWithName:#"SegoeWP" size:15];
[self.navigationController.navigationBar addSubview:self.navBarBackLabel];
self.tableView.delegate = self;
self.tableView.dataSource = self;
self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.tableView.bounds.size.width, 0.01f)];
self.tableView.contentInset = UIEdgeInsetsZero;
self.viewOrderSummaryArray = [[NSMutableArray alloc] init];
[self setupTableViewHeader];
}
#pragma mark - UITableViewDataSource
- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 30.0f;
}
- (UIView*) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
CGRect frame = tableView.frame;
self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
self.headerView.backgroundColor = [UIColor appOrderScreenHeaderBackgroundColor];
self.headerViewWhite = [[UIView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, 30.0f)];
self.headerViewWhite.backgroundColor = [UIColor appYellowColor];
[self.headerViewWhite addSubview:self.deliNameLabel];
[self.headerView addSubview:self.headerViewWhite];
return self.headerView;
}
- (NSString*) tableView:(UITableView *) tableView titleForHeaderInSection:(NSInteger)section
{
return nil;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 115;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.viewOrderSummaryArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
ViewOrderSummaryCell *cell = (ViewOrderSummaryCell *)[tableView dequeueReusableCellWithIdentifier:#"ViewOrderSummaryCell"];
cell.separatorInset = UIEdgeInsetsZero;
self.tableView.separatorInset = UIEdgeInsetsZero;
self.edgesForExtendedLayout = UIRectEdgeNone;
//self.tableView.layoutMargins = UIEdgeInsetsZero;
//cell.layoutMargins = UIEdgeInsetsZero;
NSDictionary* currentItem = [self.viewOrderSummaryArray objectAtIndex: indexPath.row];
cell.productNameLabel.text = [currentItem objectForKey: #"description"];
cell.productPriceLabel.text = [NSString stringWithFormat: #"%#%# x %#",[currentItem objectForKey: #"currency"],[currentItem objectForKey: #"price"], [currentItem objectForKey: #"quantity"]]; // TODO: Must implement this later
[cell.productImageView sd_setImageWithURL:[currentItem objectForKey: #"imageUrlString"] placeholderImage:[UIImage imageNamed:#"appPlaceholderImage"]];
CALayer * l = [cell.productImageView layer];
[l setMasksToBounds:YES];
[l setCornerRadius:10.0];
float sumq = 0;
NSArray *array = [self.viewOrderSummaryArray valueForKey:#"price"];
for (NSNumber *num in array)
{
sumq += [num floatValue];
}
float currentPrice = [[currentItem objectForKey: #"price"] floatValue];
float quantity = [[currentItem objectForKey: #"quantity"] intValue];
sumPrice += (currentPrice * quantity);
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return YES if you 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) {
//add code here for when you hit delete
NSLog(#"Selected row of section >> %ld",(long)indexPath.row);
NSLog(#"Selected row is %#", [self.viewOrderSummaryArray objectAtIndex:[indexPath row]] );
NSMutableDictionary* currentItem = [self.viewOrderSummaryArray objectAtIndex: indexPath.row];
if ([[currentItem objectForKey: #"quantity"] isEqualToString:#"1"]) {
[self.viewOrderSummaryArray removeObject:[self.viewOrderSummaryArray objectAtIndex:[indexPath row]]];
NSLog(#"Quantity label");
}
else {
self.quantity--;
[currentItem setObject: [NSString stringWithFormat: #"%d", self.quantity] forKey: #"quantity"];
[self.newestViewOrderSummaryArray removeObject: currentItem];
self.viewOrderSummaryArray = [[NSMutableArray alloc] initWithArray: self.newestViewOrderSummaryArray];
[self.viewOrderSummaryArray addObject: currentItem];
NSLog(#"Many label");
}
[self.tableView reloadData];
}
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
return NO;
}

SDWebImage Library is not working?

I used SDWebImage library to download images from server. In my code I am facing an image loading issue & SDwebImage. The problem is: I've written the code like this:
[cell.imgNews setImageWithURL:[NSURL URLWithString:[self.arrImages objectAtIndex:indexPath.row]]
If I give I like this my Application is working smooth & fast. But the images are not loading. It's displaying only empty cells. The Reason of displaying the empty cell is a couple of images are named in Arabic and in that the names are having space Ex.%20.
My question is: how can we display the Arabic named images (you can see the bellow screen shot) in the image cell? (Note: Few images are being displayed that are named in English)
But the Images are downloading in the Debugger Area (You can see the Screen shot here)
To Escape that empty cell I used this code:
[cell.imgNews setImageWithURL:[NSURL URLWithString:[[self.arrImages objectAtIndex:indexPath.row] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]
The Problem is if I use this code, the application gets very slow. How can I solve this Issue?
Can any one help me to solve this issue?
Here is my Code :
NewsViewController.m
#import "NewsViewController.h"
#import "NewsTableViewCell.h"
#import "NewDetailsViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "SearchVC.h"
#interface NewsViewController ()
{
NSString *temString;
NSMutableString *strTemp;
BOOL isDateSearch;
int search;
}
#property(strong,nonatomic) NSArray *SearchResultsArray;
#end
#implementation NewsViewController
#synthesize arrImages;
#synthesize TittleOne;
#synthesize TittleTwo;
#synthesize TittleThree;
#synthesize datepicker;
#synthesize PickerContainer;
#synthesize datepickerTittle;
#synthesize searchBr;
#synthesize NewsIndicator;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
#pragma mark - View Life Cycle
- (void)viewDidLoad
{
[self performSelector:#selector(myindicator) withObject:nil afterDelay:10.0];
[super viewDidLoad];
search=0;
self.searchBr.hidden=YES;
self.searchBr.barTintColor = UIColorFromRGB(0Xe54c41);
self.searchBr.backgroundColor = UIColorFromRGB(0Xe54c41);
[self removeUISearchBarBackgroundInViewHierarchy:self.searchDisplayController.searchBar];
self.searchDisplayController.searchBar.backgroundColor = NO;
[TittleOne setFont: [UIFont fontWithName:#"GEEast-ExtraBold" size:12]];
[TittleTwo setFont: [UIFont fontWithName:#"GEEast-ExtraBold" size:12]];
[TittleThree setFont: [UIFont fontWithName:#"GEEast-ExtraBold" size:10]];
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"dd/MM/yyyy"];
NSLog(#"%#",[dateFormatter stringFromDate:[NSDate date]]);
[TittleTwo setText:[dateFormatter stringFromDate:[NSDate date]]];
// [[UIColor redColor] set];
[datepickerTittle setFont:[UIFont fontWithName:#"GEEast-ExtraBold" size:12]];
// [datepickerTittle.textColor= [UIColor yellowColor]];
isDateSearch=NO;
self.arrTitles =[[NSMutableArray alloc] init];
self.arrDescription=[[NSMutableArray alloc]init];
self.arrImages=[[NSMutableArray alloc]init];
self.arrDate=[[NSMutableArray alloc]init];
self.arrUrls=[[NSMutableArray alloc]init];
self.arrDateSearch=[[NSMutableArray alloc]init];
//[self performSelectorInBackground:#selector(requestingForNews:) withObject:nil];
// dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), s^{
self.spinnerView.hidden=YES;
[self makeRequestForNews];
// self.spinnerView.stopAnimating;
//});
// Do any additional setup after loading the view.
[self imagedownloader:#"http://www.shura.bh/MediaCenter/News/"];
self.SearchResultsArray = [[NSArray alloc] init ];
}
-(void)myindicator {
[NewsIndicator stopAnimating];
NewsIndicator.hidden =YES;
[self.tblNews reloadData];
}
-(void)requestingForNews:(id)sender
{
[self makeRequestForNews];
}
-(void) imagedownloader : (NSString *)urlStringOfImage
{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
//downlaod image
NSURL *imageUrl = [NSURL URLWithString:urlStringOfImage];
NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
UIImage *image = [UIImage imageWithData:imageData];
dispatch_async(dispatch_get_main_queue(), ^{
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50 )];
imageView.image = image;
[self.view addSubview:imageView];
});
});
}
- (void) removeUISearchBarBackgroundInViewHierarchy:(UIView *)view
{
for (UIView *subview in [view subviews]) {
if ([subview isKindOfClass:NSClassFromString(#"UISearchBarBackground")]) {
[subview removeFromSuperview];
break; //To avoid an extra loop as there is only one UISearchBarBackground
} else {
[self removeUISearchBarBackgroundInViewHierarchy:subview];
}
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - make request for news
-(void)makeRequestForNews
{
NSURL *url =[NSURL URLWithString:self.strNewsApi];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//After making request the apparent thing is expecting the response that may be expected response or an Error. so create those objects and intialize them with NULL.
NSURLResponse *response = NULL;
NSError *requestError =NULL;
//Once you have response with you , Capture YOur Responce data using NsData.
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
//Convert the respnse Data into Response String.
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
//Now We can start parsing the Data using XMl parser . you need XML parser in-order to use the below class method "dictionaryFOrXMLString".
NSError *parserError = NULL;
//XML parsing
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:responseData];
[xmlParser setDelegate:self];
[xmlParser parse];
// NSURL *url = [NSURL URLWithString:url];
// NSData *data = [NSData dataWithContentsOfURL:url];
// UIImage *image = [UIImage imageWithData:data];
//NSDictionary *xmlDict = [XMLReader dictionaryForXMLString:responseString error:NULL];
//once you have xmlDict handy, you can pass this to the any ViewController (Like table view) to populate the Data.
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:#"ShuraNews"])
{
}
if ([elementName isEqualToString:#"PUBLISHINGPAGEIMAGE"])
{
}
strTemp=[NSMutableString new];
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
//temString =string;
[strTemp appendString:string];
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:#"TITLE"])
{
NSLog(#"temstring=== %#", strTemp);
[self.arrTitles addObject:strTemp];
}
if ([elementName isEqualToString:#"PUBLISHINGPAGECONTENT"])
{
NSLog(#"temstring=== %#", strTemp);
[self.arrDescription addObject:strTemp];
}
if ([elementName isEqualToString:#"NEWSARTICLEDATE"])
{
NSLog(#"temstring=== %#", strTemp);
[self.arrDate addObject:strTemp];
}
if ([elementName isEqualToString:#"PUBLISHINGPAGEIMAGE"])
{
NSLog(#"temstring=== %#", strTemp);
[self.arrImages addObject:strTemp];
}
if ([elementName isEqualToString:#"ShuraNews"])
{
[self.tblNews reloadData];
// self.spinnerView.hidden=YES;
}
if ([elementName isEqualToString:#"URL"])
{
[self.arrUrls addObject:strTemp];
}
}
#pragma mark - TabeView Datasource//delegate method
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView)
{
return [self.SearchResultsArray count];
}
else
{
return [self.arrTitles count];
}
if (isDateSearch)
{
return [self.arrDateSearch count];
}
else{
return [self.arrTitles count];
}
return [self.arrTitles count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView setSeparatorInset:UIEdgeInsetsZero];
static NSString *cellIdentifier=#"cellNews";
NewsTableViewCell *cell=(NewsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
// NewsTableViewCell *cell=(NewsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if (cell == nil)
{
cell = [[NewsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
// cell.NewsTableViewCell.textColor = UIColorFromRGB(0x000000);
cell.backgroundColor=[UIColor clearColor];
}
if (tableView == self.searchDisplayController.searchResultsTableView)
{
cell.textLabel.text= [self.SearchResultsArray objectAtIndex:indexPath.row];
}
if( [indexPath row] % 2){
cell.contentView.backgroundColor =UIColorFromRGB(0Xffffff);
}
else{
cell.contentView.backgroundColor =UIColorFromRGB (0Xdcdcdc);
}
//selectbackground color start
UIView *NewsTableViewCell = [[UIView alloc] initWithFrame:cell.frame];
NewsTableViewCell.backgroundColor = UIColorFromRGB(0Xdcdcdc);
cell.selectedBackgroundView = NewsTableViewCell; //select background colro end
cell.lblTitles.font = [UIFont fontWithName:#"GEEast-ExtraBold" size:12];
if (isDateSearch)
{
cell.lblTitles.text=[[self.arrDateSearch objectAtIndex:indexPath.row]objectForKey:#"title"];
}
else{
cell.lblTitles.text=[self.arrTitles objectAtIndex:indexPath.row];
}
cell.lblDescription.font =[UIFont fontWithName:#"GE SS Unique" size:12];
cell.lblDate.font=[UIFont fontWithName:#"GE SS Unique" size:12];
if (isDateSearch)
{
cell.lblDescription.text=[[self.arrDateSearch objectAtIndex:indexPath.row]objectForKey:#"des"];
}
else{
cell.lblDescription.text=[self.arrDescription objectAtIndex:indexPath.row];
}
cell.lblDate.text=[self.arrDate objectAtIndex:indexPath.row];
cell.lblTitles.textAlignment= NSTextAlignmentRight;
cell.lblDate.textAlignment = NSTextAlignmentRight;
cell.lblDescription.textAlignment = NSTextAlignmentRight;
NSData *data;
if (isDateSearch)
{
data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[self.arrDateSearch objectAtIndex:indexPath.row]objectForKey:#"img"]]];
}
else{
data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[self.arrImages objectAtIndex:indexPath.row]]];
}
//SDWebImage Code for lazy loader
[cell.imgNews setImageWithURL: //[NSURL URLWithString:[self.arrImages objectAtIndex:indexPath.row]]
[NSURL URLWithString:[[self.arrImages objectAtIndex:indexPath.row] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
// if (![self.arrImages objectAtIndex:indexPath.row])
// if ((cell.imgNews.image = image))
if (image)
{
cell.imgNews.layer.borderColor = [UIColor blackColor].CGColor;
cell.imgNews.layer.borderWidth = 2.0;
cell.lblTitles.frame=CGRectMake(cell.lblTitles.frame.origin.x, cell.lblTitles.frame.origin.y, 208, cell.lblTitles.frame.size.height);
cell.lblDate.frame=CGRectMake(cell.lblDate.frame.origin.x, cell.lblDate.frame.origin.y, 208, cell.lblDate.frame.size.height);
cell.lblDescription.frame=CGRectMake(cell.lblDescription.frame.origin.x, cell.lblDescription.frame.origin.y, 206, cell.lblDescription.frame.size.height);
}
else {
// if (!cell.imgNews ==nil)
if (!cell.imgNews.image)
{
cell.lblTitles.frame=CGRectMake(cell.lblTitles.frame.origin.x, cell.lblTitles.frame.origin.y, 283, cell.lblTitles.frame.size.height);
cell.lblDate.frame=CGRectMake(cell.lblDate.frame.origin.x, cell.lblDate.frame.origin.y, 286, cell.lblDate.frame.size.height);
cell.lblDescription.frame=CGRectMake(cell.lblDescription.frame.origin.x, cell.lblDescription.frame.origin.y, 281, cell.lblDescription.frame.size.height);
cell.imgNews.layer.borderColor = [UIColor blackColor].CGColor;
cell.imgNews.layer.borderWidth = 0;
}
}
}];
[PickerContainer setHidden:YES];
return cell;
}
#pragma Search Methods
-(void)filterContentForSearchText:(NSString *)searchText scope:(NSString *)scope
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains [search] %#", searchText];
self.SearchResultsArray = [self.arrTitles filteredArrayUsingPredicate:predicate];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
return YES;
}
- (void)layoutSubviews
{
if(!(searchBr == nil))
{
searchBr.frame = CGRectMake(4, 5, 185, 30);
}
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *dict=nil;
if (isDateSearch)
{
dict=[[NSDictionary alloc]initWithObjectsAndKeys:[NSString stringWithFormat:#"%#",[[self.arrDateSearch objectAtIndex:indexPath.row]objectForKey:#"title"]],#"title",[NSString stringWithFormat:#"%#",[[self.arrDateSearch objectAtIndex:indexPath.row]objectForKey:#"des"]],#"img",[NSString stringWithFormat:#"%#",[self.arrDescription objectAtIndex:indexPath.row]],#"Des",[NSString stringWithFormat:#"%#",[self.arrUrls objectAtIndex:indexPath.row]],#"url", nil];
}
else{
dict=[[NSDictionary alloc]initWithObjectsAndKeys:[NSString stringWithFormat:#"%#",
[self.arrTitles objectAtIndex:indexPath.row]],#"title",[NSString stringWithFormat:#"%#",
[self.arrImages objectAtIndex:indexPath.row]],#"img",[NSString stringWithFormat:#"%#",
[self.arrDescription objectAtIndex:indexPath.row]],#"Des",[NSString stringWithFormat:#"%#",
[self.arrDate objectAtIndex:indexPath.row]],#"Date",[NSString stringWithFormat:#"%#",
[self.arrUrls objectAtIndex:indexPath.row]],#"url", nil];
}
[self performSegueWithIdentifier:#"NewsDetailsID" sender:dict];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"NewsDetailsID"])
{
((NewDetailsViewController *)segue.destinationViewController).strTitle=[sender objectForKey:#"title"];
((NewDetailsViewController *)segue.destinationViewController).strDetailImage=[sender objectForKey:#"img"];
((NewDetailsViewController *)segue.destinationViewController).strDescription=[sender objectForKey:#"Des"];//strUrl
((NewDetailsViewController *)segue.destinationViewController).strDate=[sender objectForKey:#"Date"];
((NewDetailsViewController *)segue.destinationViewController).strUrl=[sender objectForKey:#"url"];
}
}
- (IBAction)SearchButton:(id)sender {
if (search == 0) {
searchBr.hidden=NO;
search=1;
}
else
{
searchBr.hidden=YES;
search=0;
}
}
- (IBAction)backBtnClicked:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)DatePickerBt:(id)sender {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
PickerContainer.frame = CGRectMake(0, 150, 320, 261);
[PickerContainer setHidden:NO];
}
- (IBAction)HideButton:(id)sender
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
PickerContainer.frame = CGRectMake(0,600, 320, 261);
[UIView commitAnimations];
if ([self.arrDate count])
{
for (int i=0; i<[self.arrDate count]; i++)
{
NSArray *arrDateStr=[[self.arrDate objectAtIndex:i] componentsSeparatedByString:#" "];
// NSString *dateString=[NSString stringWithFormat:#"%# %#",[[arrDateStr objectAtIndex:0]stringByReplacingOccurrencesOfString:#"/" withString:#"-"],[arrDateStr objectAtIndex:1]];
NSString *dateString=[NSString stringWithFormat:#"%# %#",[arrDateStr objectAtIndex:0],[arrDateStr objectAtIndex:1]];
NSDateFormatter *format = [[NSDateFormatter alloc]init];
[format setDateFormat:#"dd/MM/yyyy"];
NSDate *currentDate = [format dateFromString:dateString];
if ([[[[NSString stringWithFormat:#"%#",currentDate]componentsSeparatedByString:#" "]objectAtIndex:0] isEqualToString:[[[NSString stringWithFormat:#"%#",self.datepicker.date]componentsSeparatedByString:#" "]objectAtIndex:0]])
{
isDateSearch=YES;
NSDictionary *dictTemp=[NSDictionary dictionaryWithObjectsAndKeys:[self.arrTitles objectAtIndex:i],#"title",[self.arrDescription objectAtIndex:i],#"des",[self.arrImages objectAtIndex:i],#"img", nil];
[self.arrDateSearch addObject:dictTemp];
[self.tblNews reloadData];
NSLog(#"dates equal");
}
}
}
}
- (IBAction)ReloadButton:(id)sender {
self.spinnerView.hidden=YES;
isDateSearch=NO;
[self makeRequestForNews];
NSLog(#"RELOADING!!!!!!!!!!!!!!!");
}
#end
You should definitely be using stringByAddingPercentEscapesUsingEncoding, and I do not think that this is "per se" causing the performance problem you see. That is just modifying a bit the URL you use.
I tend to think that by using stringByAddingPercentEscapesUsingEncoding your app is getting all of the images (as opposed to just a few of them) and this is making it slower.
E.g., if the images you download are large, then this might explain the app slowness, both in terms of how long you have to wait for the image to be available and to scale it down to cell size.
EDIT:
I checked the site http://www.shura.bh/MediaCenter/News and images are indeed large. They take quite a while to download in Safari. I have found images as large as 4000x3000px, and this is definitely too large.

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]

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