How to set badge value in Tab bar? - ios

i have to read datas from xml and have to display values in view controller. am using tab barcontroller . where i have to read xml data and have to display it in tab bar as badge. here is my controller code.
-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
if([elementName isEqualToString:#"Event"]) {
//Initialize the array.
rssOutputData = [[NSMutableArray alloc] init];
mycount = [attributeDict objectForKey:#"count"];
NSLog(#"Reading count value :%#",mycount);
}
else if([elementName isEqualToString:#"eventdashboard"]) {
//Initialize the book.
aEvent = [[Eventlist alloc] init];
//Extract the attribute here.
aEvent.id = [[attributeDict objectForKey:#"userid"] integerValue];
NSLog(#"Reading id value :%d", aEvent.id);
}
NSLog(#"Processing Element: %#", elementName);
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if(!nodecontent)
nodecontent = [[NSMutableString alloc] initWithString:string];else
[nodecontent appendString:string];
NSLog(#"Processing Value: %#", nodecontent);
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if([elementName isEqualToString:#"Event"])
return;
if([elementName isEqualToString:#"eventdashboard"]) {
[rssOutputData addObject:aEvent];
[aEvent release];
aEvent= nil;
}
else
[aEvent setValue:nodecontent forKey:elementName];
[nodecontent release];
nodecontent = nil;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"bg2.jpeg"]];
NSLog(#"%d",memberid);
myid = [SingleTonClass sinlgeTon].memberIdOne;
NSString *post =[[NSString alloc] initWithFormat:#"userid=%d",myid];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSURL *url = [NSURL URLWithString:#"http://journalonline.in/cfts/dashboards/dashboard?"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
// [theRequest addRequestHeader:#"Content-Type" value:#"application/xml"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:#"application/xml" forHTTPHeaderField:#"Accept"];
[theRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[theRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
webData = [[NSMutableData data] retain];
NSLog(#"%#",webData);
}
}
-(void)viewWillAppear:(BOOL)animated{
[tblView reloadData];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
eventarray = [[NSMutableArray alloc]init];
xmlParserObject = [[NSXMLParser alloc] initWithData:webData];
[xmlParserObject setDelegate:self];
[xmlParserObject parse];
for (int i =0; i<[rssOutputData count]; i++) {
Eventlist *log = [rssOutputData objectAtIndex:i];
eventid = log.id;
NSLog(#"%d",eventid);
Invit = log.invitationdet;
NSLog(#"%#",Invit);
[eventarray addObject:log];
}
[connection release];
[tblView reloadData];
}
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
NSString * segueIdentifier = [segue identifier];
if([segueIdentifier isEqualToString:#"MainEventList"]){
UINavigationController *nav = [segue destinationViewController];
MaineventListController *MVC = (MaineventListController *)nav.topViewController;
MVC.memberid1 = [SingleTonClass sinlgeTon].memberIdOne;
NSLog(#"%d",MVC.memberid1);
}
if ([segue.identifier isEqualToString:#"EventListDetail"])
{
NSIndexPath *indexPath = [tblView indexPathForSelectedRow];
[[SingleTonClass sinlgeTon] addObjectsColorArray:[NSString stringWithFormat:#"%d",indexPath.row]];
MainEventDetailController *destViewController = segue.destinationViewController;
MainEvent *aEvent1 = [eventarray objectAtIndex:indexPath.row];
destViewController.eveID = aEvent1.id;
destViewController.usrid = [SingleTonClass sinlgeTon].memberIdOne;
}
}
-(void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [eventarray count];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section == 0)
return [eventarray count];
if (section == 1)
return 1;
return 0;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"eventCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if(indexPath.section == 0)
{
Eventlist *msglist = [eventarray objectAtIndex:indexPath.row];
cell.textLabel.text = msglist.invitationdet;
NSLog(#"Array %#",[SingleTonClass sinlgeTon].colorArray);
NSInteger stat=msglist.readflag;
if([[SingleTonClass sinlgeTon].colorArray containsObject:[NSString stringWithFormat:#"%d",indexPath.row]] || stat == 1 ) {
NSInteger stat1 = msglist.responseflag;
if(stat1 == 1){
cell.textLabel.textColor = [UIColor yellowColor];
}
else {
cell.textLabel.textColor = [UIColor redColor];
}
}
else{
cell.textLabel.textColor = [UIColor greenColor];
}
cell.backgroundColor = [UIColor blackColor];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
if(indexPath.section == 1)
{
UIButton *viewmoreButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
viewmoreButton.frame = CGRectMake(200.0f, 5.0f, 80.0f, 30.0f);
[viewmoreButton setTitle:#"View More" forState:UIControlStateNormal];
[cell addSubview:viewmoreButton];
[viewmoreButton addTarget:self
action:#selector(viewMore:)
forControlEvents:UIControlEventTouchUpInside];
cell.backgroundColor = [ UIColor blackColor];
}
return cell;
}
- (void)viewMore:(id)sender
{
[self performSegueWithIdentifier:#"MainEventList" sender:sender];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(void) dealloc
{
[xmlParserObject release];
[super dealloc];
}
Here am reading a value from XML
mycount = [attributeDict objectForKey:#"count"];
I dont know to display in tab bar as badge. i tried to display it under ViewdidLoad but didnt worked
pls help me friends

Let me tell you the simplest way to set badge value :
[[self navigationController] tabBarItem].badgeValue = #"YourBadgeValue";

Vineet Singh's answer is good if you want to change the badge for the current tab. If instead you need to change the value for another tab you have in your tab bar, use the following:
Objective-C
[[self.tabBarController.tabBar.items objectAtIndex:0] setBadgeValue:nil];
Swift
tabBarController?.tabBar.items?[0].badgeValue = nil
Remember to replace the index I used with the actual tab you want to edit the value for.

AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
UITabBarItem *tbItem = (UITabBarItem *)[appDelegate.tabBarController.tabBar.items objectAtIndex:tabIndex];
tbItem.badgeValue = [NSString stringWithFormat:#"%i", count];

swift 2.0:
self.navigationController!.tabBarItem.badgeValue = "YourBadgeValue"

Try this:
tabBarItem.badgeValue = [NSString stringWithFormat:#"%d",count];

I see some answers about setting this on the TabItem, but if the tab has never been loaded the viewDidLoad function will never get loaded. This is especially important when you are trying to create a background process such as push notification handling set a tab's badge. It's much more likely you will need your TabViewController to handle the badge setting. Tags on the TabItem seem more appropriate and then flip through the tabs until you find the one you want to update.
Cheers!

int indexOfTabbarItem = 0;
NSString *badgeValue = [NSString stringWithFormat:#"%lu", (long)countUnreadMessages];
[[[[self viewControllers] objectAtIndex:indexOfTabbarItem] tabBarItem] setBadgeValue:([badgeValue isEqualToString:#"0"]) ? nil : badgeValue];
This worked for me. Some times you have to find the right controller and then its item to set it. Cheers.

For ionic angular, you just bind the value to tabBadge
<ion-tab [root]="tab3Root" tabIcon="notifications" tabBadgeStyle="red" tabBadge={{totalUnread}}></ion-tab>

Related

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.

How To Search The TableviewData in Different ViewController?

I have a NewsViewController where News Displaying Form XML , My Problem is I Created Separate Class Called SearchVC and I have Added the Search Bar, Here I want search the all the News
(from NewsViewController). The Search Result Should Display in the Drop down List, If i click those Search result It should Redirect to the NewsDetailsViewController. I do not know how to do this can any one help me out of this issue .
Here is my NewsViewController.m
#import "NewsViewController.h"
#import "NewsTableViewCell.h"
#import "NewDetailsViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#interface NewsViewController ()
{
NSString *temString;
NSMutableString *strTemp;
}
#end
#implementation NewsViewController
#synthesize arrImages;
#synthesize TittleOne;
#synthesize TittleTwo;
#synthesize TittleThree;
#synthesize datepicker;
#synthesize PickerContainer;
#synthesize datepickerTittle;
- (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
{
[TittleOne setFont: [UIFont fontWithName:#"GEEast-ExtraBold" size:12]];
[TittleTwo setFont: [UIFont fontWithName:#"GEEast-ExtraBold" size:10]];
[TittleThree setFont: [UIFont fontWithName:#"GEEast-ExtraBold" size:10]];
// [[UIColor redColor] set];
[datepickerTittle setFont:[UIFont fontWithName:#"GEEast-ExtraBold" size:12]];
// [datepickerTittle.textColor= [UIColor yellowColor]];
[super viewDidLoad];
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 performSelectorInBackground:#selector(requestingForNews:) withObject:nil];
// dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), s^{
self.spinnerView.hidden=NO;
[self makeRequestForNews];
// self.spinnerView.stopAnimating;
//});
// Do any additional setup after loading the view.
[self imagedownloader:#"http://www.shura.bh/MediaCenter/News/"];
}
-(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)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
{
return [self.arrTitles count];
//
// NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
// [dateFormatter setTimeStyle:NSDateFormatterFullStyle];
// [dateFormatter setDateFormat:#"dd mmm yyyy"];
// [datepicker sortUsingComparator:^(id dateObje1,id dateObje2)
// {
// NSDate *date1 = [dateFormatter dateFromString:[(datepicker) dateObje1 arrDate]];
// NSDate *date2 = [dateFormatter dateFromString:[(datepicker) dateObje2 arrDate]];
// return [date2 compare:date1];
// }
// ];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView setSeparatorInset:UIEdgeInsetsZero];
static NSString *cellIdentifier=#"cellNews";
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];
//SDWebImage Code for lazy loader
[cell.imgNews setImageWithURL:[NSURL URLWithString:[self.arrImages objectAtIndex:indexPath.row]] placeholderImage:[UIImage imageNamed:#"placeholder.gif"]];
}
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];
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];
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;
//cell.imageView.image = [UIImage imageNamed:[arrImages objectAtIndex:indexPath.row]];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[self.arrImages objectAtIndex:indexPath.row]]];
cell.imgNews.image=[UIImage imageWithData:data];
cell.imgNews.layer.borderColor = [UIColor blackColor].CGColor;
cell.imgNews.layer.borderWidth = 2.0;
[PickerContainer setHidden:YES];
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;
}
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *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.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).strUrl=[sender objectForKey:#"url"];
}
}
- (IBAction)backBtnClicked:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
}
#end
Thanks In Advance.
As far as searching is concerned, You'll have to search your arrays in the NewsViewController, based on keywords that the user enters and if any results are returned, the perform a segue to your NewsDetailsViewController where those results will be displayed. For performing segue to the NewsDetailsViewController, you can use this method,
[self performSegueWithIdentifier:#"segueIdentifier" sender:nil];
Another suggestion is to use UITableViewController instead of Dropdown. The reason being that it is available in the SDK itself and you can show somewhat more data using TableView whereas Dropdown has to be made custom.

Show RSS pubDate in Table View Cell

My app uses an RSS feed to populate the cells in a table view with the titles of articles from the feed. I'm trying to add the published date for each article to the corresponding cell but it isn't showing up. The titles show up just fine in as the textLabel but the date is not showing in the detailTextLabel. I have an NSLog that shows all of the pubDate items and a NSLog in didSelectRowAtIndexPath that shows the pubDate for the selected row. Any help?
RSSChannel.m
#import "RSSChannel.h"
#import "RSSItem.h"
#implementation RSSChannel
#synthesize items, title, infoString, parentParserDelegate, date;
- (id)init
{
self = [super init];
if (self)
{
// Create the container for the RSSItems this channel has
items = [[NSMutableArray alloc]init];
}
return self;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
NSLog(#"\t%# found a %# element", self, elementName);
if ([elementName isEqual:#"title"])
{
currentString = [[NSMutableString alloc]init];
[self setTitle:currentString];
}
else if ([elementName isEqual:#"pubDate"])
{
currentString = [[NSMutableString alloc]init];
[self setDate:currentString];
}
else if ([elementName isEqual:#"description"])
{
currentString = [[NSMutableString alloc]init];
[self setInfoString:currentString];
}
else if ([elementName isEqual:#"item"])
{
RSSItem *entry = [[RSSItem alloc]init];
// Set up its parent as ourselves so we can regain control of the parser
[entry setParentParserDelegate:self];
// Turn the parser to the RSSItem
[parser setDelegate:entry];
[items addObject:entry];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)str
{
[currentString appendString:str];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
currentString = nil;
if ([elementName isEqual:#"channel"])
{
[parser setDelegate:parentParserDelegate];
}
}
#end
RSSItem.m
#import "RSSItem.h"
#implementation RSSItem
#synthesize title, link, date, isActionAlert, parentParserDelegate;
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
NSLog(#"\t\t%# found a %# element", self, elementName);
if ([elementName isEqualToString:#"category"]) {
NSLog(#"category");
}
if ([elementName isEqual:#"title"])
{
currentString = [[NSMutableString alloc]init];
[self setTitle:currentString];
}
else if ([elementName isEqual:#"link"])
{
currentString = [[NSMutableString alloc]init];
[self setLink:currentString];
}
else if ([elementName isEqual:#"pubDate"])
{
currentString = [[NSMutableString alloc]init];
[self setDate:currentString];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)str
{
if ([str isEqualToString:#"Action Alert"]) {
isActionAlert = YES;
}
[currentString appendString:str];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
currentString = nil;
if ([elementName isEqual:#"item"])
{
[parser setDelegate:parentParserDelegate];
}
}
#end
Table View Controller
#import "AgStoriesViewController.h"
#import "RSSChannel.h"
#import "RSSItem.h"
#import "WebViewController.h"
// #import "CustomCellBackground.h"
#import "DTCustomColoredAccessory.h"
#implementation AgStoriesViewController
{
UIActivityIndicatorView *loadingIndicator;
}
#synthesize webViewController;
- (void)viewDidLoad
{
UIImageView *background = [[UIImageView alloc]init];
background.image = [UIImage imageNamed:#"plain_app-background.png"];
CGFloat width = CGRectGetWidth(self.view.bounds);
CGFloat height = CGRectGetHeight(self.view.bounds);
self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
[self.tableView setBackgroundView:background];
self.title = #"Ag News";
loadingIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
loadingIndicator.center = CGPointMake(width/2, height/2);
loadingIndicator.hidesWhenStopped = YES;
[self.view addSubview:loadingIndicator];
[loadingIndicator startAnimating];
// UIRefreshControl *refresh = [[UIRefreshControl alloc] init];
// refresh.attributedTitle = [[NSAttributedString alloc] initWithString:#"Pull to Refresh"];
// [refresh addTarget:self action:#selector(refreshView:)forControlEvents:UIControlEventValueChanged];
// self.refreshControl = refresh;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
NSLog(#"%# found a %# element", self, elementName);
if ([elementName isEqual:#"channel"])
{
// If the parser saw a channel, create new instance, store in our ivar
channel = [[RSSChannel alloc]init];
// Give the channel object a pointer back to ourselves for later
[channel setParentParserDelegate:self];
// Set the parser's delegate to the channel object
[parser setDelegate:channel];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// return 0;
NSLog(#"channel items %d", [[channel items]count]);
return [[channel items]count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 50;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// return nil;
UIImageView *image = [[UIImageView alloc]init];
image.image = [UIImage imageNamed:#"CellImage.png"];
UIImageView *background = [[UIImageView alloc]init];
background.image = [UIImage imageNamed:#"plain_app-background.png"];
UIImageView *highlightedCellImage = [[UIImageView alloc]init];
highlightedCellImage.image = [UIImage imageNamed:#"HighlightedCellImage"];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"UITableViewCell"];
if (cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"UITableViewCell"];
cell.textLabel.font=[UIFont systemFontOfSize:16.0];
}
RSSItem *item = [[channel items]objectAtIndex:[indexPath row]];
[[cell textLabel]setText:[item title]];
[[cell detailTextLabel]setText:[item date]];
NSLog(#"Date: %#", [item date]);
tableView.backgroundColor = [UIColor clearColor];
// cell.backgroundView = [[CustomCellBackground alloc] init];
// cell.selectedBackgroundView = [[CustomCellBackground alloc] init];
cell.textLabel.backgroundColor = [UIColor clearColor];
cell.textLabel.highlightedTextColor = [UIColor blueColor];
cell.textLabel.font = [UIFont fontWithName:#"FranklinGothicStd-ExtraCond" size:20.0];
cell.textLabel.textColor = [UIColor whiteColor];
cell.detailTextLabel.backgroundColor = [UIColor clearColor];
cell.detailTextLabel.highlightedTextColor = [UIColor blueColor];
cell.detailTextLabel.font = [UIFont fontWithName:#"FranklinGothicStd-ExtraCond" size:16.0];
cell.detailTextLabel.textColor = [UIColor whiteColor];
cell.backgroundView = image;
cell.selectedBackgroundView = highlightedCellImage;
tableView.backgroundView = background;
DTCustomColoredAccessory *accessory = [DTCustomColoredAccessory accessoryWithColor:cell.textLabel.textColor];
accessory.highlightedColor = [UIColor blueColor];
cell.accessoryView =accessory;
return cell;
}
- (void)fetchEntries
{
// Create a new data container for the stuff that comes back from the service
xmlData = [[NSMutableData alloc]init];
// Construct a URL that will ask the service for what you want -
// note we can concatenate literal strings together on multiple lines in this way - this results in a single NSString instance
NSURL *url = [NSURL URLWithString:#"http://kyfbnewsroom.com/category/ag-news/feed"];
// Put that URL into an NSURLRequest
NSURLRequest *req = [NSURLRequest requestWithURL:url];
// Create a connection that will exchange this request for data from the URL
connection = [[NSURLConnection alloc]initWithRequest:req delegate:self startImmediately:YES];
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self)
{
[self fetchEntries];
}
return self;
}
// This method will be called several times as the data arrives
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
// Add the incoming chunk of data to the container we are keeping
// The data always comes in the correct order
[xmlData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
/* We are just checking to make sure we are getting the XML
NSString *xmlCheck = [[NSString alloc]initWithData:xmlData encoding:NSUTF8StringEncoding];
NSLog(#"xmlCheck = %#", xmlCheck);*/
[loadingIndicator stopAnimating];
// Create the parser object with the data received from the web service
NSXMLParser *parser = [[NSXMLParser alloc]initWithData:xmlData];
// Give it a delegate
[parser setDelegate:self];
//Tell it to start parsing - the document will be parsed and the delegate of NSXMLParser will get all of its delegate messages sent to it before this line finishes execution - it is blocking
[parser parse];
// Get rid of the XML data as we no longer need it
xmlData = nil;
// Reload the table.. for now, the table will be empty
[[self tableView]reloadData];
NSLog(#"%#\n %#\n %#\n", channel, [channel title], [channel infoString]);
}
- (void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error
{
// Release the connection object, we're done with it
connection = nil;
// Release the xmlData object, we're done with it
xmlData = nil;
// Grab the description of the error object passed to us
NSString *errorString = [NSString stringWithFormat:#"Fetch failed: %#", [error localizedDescription]];
// Create and show an alert view with this error displayed
UIAlertView *av = [[UIAlertView alloc]initWithTitle:#"Error" message:errorString delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[av show];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Push the web view controller onto the navigation stack - this implicitly creates the web view controller's view the first time through
// [[self navigationController]pushViewController:webViewController animated:YES];
[self.navigationController pushViewController:webViewController animated:NO];
// Grab the selected item
RSSItem *entry = [[channel items]objectAtIndex:[indexPath row]];
NSLog(#"Channel Items: %#", [[channel items]objectAtIndex:[indexPath row]]);
// Construct a URL with the link string of the item
NSURL *url = [NSURL URLWithString:[entry link]];
NSLog(#"Link: %#", [entry link]);
// Construct a request object with that URL
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSLog(#"URL: %#", url);
// Load the request into the web view
[[webViewController webView]loadRequest:req];
webViewController.hackyURL = url;
NSLog(#"Request: %#", req);
// Set the title of the web view controller's navigation item
// [[webViewController navigationItem]setTitle:[entry title]];
NSLog(#"Title: %#", [entry title]);
NSLog(#"Pub Date: %#", [entry date]);
}
#end
You're using UITableViewCellStyleDefault when constructing your cell. This style does not provide the detailTextLabel. You should probably take UITableViewCellStyleSubtitle.

Failure to display data in UITableView

I have a UITableView that has to be populated with the contents stored in an array. I have displayed the array in the NSLog which comes out just fine but it is not visible in the uitableview. The problem is that the program does not enter the cellForRowAtIndexPath method. I am not sure as to which code i should be adding to this question to make it easier to understand so please ask me for the code.
#import "SubList.h"
#import "SubListParser.h"
#import "LoginParser.h"
#implementation SubList
#synthesize theXML1,FolderID,UserID;
NSString *loginUserId;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
self.FolderID=FolderID ;
self.UserID=UserID;
}
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.
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self initWithData];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
-(void)initWithData{
//[self GetChilds:FolderID UserID:loginUserId];
}
-(void)GetUserLoginId:(NSString *)UserIdReceved{
loginUserId=UserIdReceved;
}
-(void)GetChilds:(NSString*)FolderIDRecvd UserID:(NSString*)userID{
NSString *_FolderID=FolderIDRecvd;
NSString *_UserID=loginUserId;
//?? what to do here? aa gye bhai yha pe folder id nad user id? try out now ok
// NSLog(#"hi yaar response toh aa rha ha that mean s values toh ha hmare pass haan storyboard ka koi laucha hai ny yaar do min de dekhta hu",FolderIDRecvd,loginUserId);
NSString *soapMsg=[NSString stringWithFormat:#"<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'><soap:Body><TreeDataSubFolder xmlns='http://tempuri.org/'><FolderID>%#</FolderID><UserId>%#</UserId></TreeDataSubFolder></soap:Body></soap:Envelope>",_FolderID,_UserID];
NSLog(#"%#",soapMsg);
NSURL *url=[NSURL URLWithString:#"http://192.168.1.5/interlogicsmobile/interlogics.asmx?op=TreeDataSubFolder"];
xmlparser1 = [[NSXMLParser alloc] initWithContentsOfURL:url];
NSMutableURLRequest *req=[NSMutableURLRequest requestWithURL:url];
NSString *msgLength=[NSString stringWithFormat:#"%d",[soapMsg length]];
NSLog(#"Message Length=%#",msgLength);
[req addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[req addValue:#"http://tempuri.org/TreeDataSubFolder" forHTTPHeaderField:#"SOAPAction"];
[req addValue:#"length" forHTTPHeaderField:#"Content-Length"];
[req setHTTPMethod:#"POST"];
[req setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
//[activityIndicator startAnimating];
conn1=[[NSURLConnection alloc]initWithRequest:req delegate:self];
if(conn1){
webdata1=[NSMutableData data] ;
}
}
-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) response {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
int responseStausCode = [httpResponse statusCode];
NSLog(#"code: %d", responseStausCode);
[webdata1 setLength: 0];
}
-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data {
[webdata1 appendData:data];
}
-(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error {
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
NSLog(#"DONE. Received Bytes: %d", [webdata1 length]);
theXML1 = [[NSString alloc]
initWithBytes: [webdata1 mutableBytes]
length:[webdata1 length]
encoding:NSUTF8StringEncoding];
//---shows the XML---
//NSLog(#"%#",theXML1);
SubListParser *parserObjForData1=[[SubListParser alloc]init];
SubFolderData=[[NSMutableArray alloc]init];
SubFolderData=[parserObjForData1 UserXMLParser1:webdata1];
[SublistSet reloadData];
}
- (void)viewDidUnload
{
[SublistSet reloadData];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[SublistSet reloadData];
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [SubFolderData count]/2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"*******************called tablevied did load*********************");
int row = [indexPath row]*2;
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
for (int i=0; i<=[SubFolderData count]/2; i++) {
NSString *filename = [SubFolderData objectAtIndex:row];
NSString *ext = [filename pathExtension];
if ([ext isEqualToString:#"doc"] || [ext isEqualToString:#"DOC"]) {
[cell.imageView setImage:[UIImage imageNamed:#"DOC.png"]];
} else if ([ext isEqualToString:#"jpg"]|| [ext isEqualToString:#"JPG"]) {
[cell.imageView setImage:[UIImage imageNamed:#"JPG.png"]];
}else if([ext isEqualToString:#"pdf"]|| [ext isEqualToString:#"PDF"]){
[cell.imageView setImage:[UIImage imageNamed:#"PDF.png"]];
}else if([ext isEqualToString:#""]){
[cell.imageView setImage:[UIImage imageNamed:#"Folder2.png"]];
}else if([ext isEqualToString:#"docx"]|| [ext isEqualToString:#"DOCX"]){
[cell.imageView setImage:[UIImage imageNamed:#"DOCX.png"]];
}else if([ext isEqualToString:#"TIF"]|| [ext isEqualToString:#"tif"]){
[cell.imageView setImage:[UIImage imageNamed:#"TIFF.png"]];
}else if([ext isEqualToString:#"png"]|| [ext isEqualToString:#"PNG"]){
[cell.imageView setImage:[UIImage imageNamed:#"PNG.png"]];
}else if([ext isEqualToString:#"gif"]|| [ext isEqualToString:#"GIF"]){
[cell.imageView setImage:[UIImage imageNamed:#"GIF.png"]];
}else if([ext isEqualToString:#"jpeg"]|| [ext isEqualToString:#"JPEG"]){
[cell.imageView setImage:[UIImage imageNamed:#"JPG.png"]];
}
}
// Configure the cell...
cell.textLabel.text=[SubFolderData objectAtIndex:row];
cell.detailTextLabel.text =[SubFolderData objectAtIndex:row+1];
cell.textLabel.numberOfLines = 0;
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
return cell;
}
/*
// Override to support conditional editing of the table view.
#end

iOS: App crashing, likely due to instantiation of class

I'm trying to debug a crash I'm experiencing...
I'm getting some data from a web server, so I've set up three classes:
Child
ChildConnection
ChildParser
ChildConnection contacts the web service and gets the data and starts the ChildParser, which then parse the xml and saves it as a Child object...
I've got it working in a project, where instead of having the ChildConnection, I set up the connection in the AppDelegate, and the issue I'm having in my current project is to do with delegates(at least that's what I think)... since I'm getting the error:
-[AppDelegate children]: unrecognized selector sent to instance 0x6b07e80
I'm fairly certain that the error is caused by: (NOTE: I'm pretty new to this)
- (ChildParser *) initChildParser {
self = [super init];
if(self)
{
childConnection = (ChildConnection *)[[UIApplication sharedApplication] delegate];
NSLog(#"Init");
}
return self;
}
ChildConnection.h:
#interface ChildConnection : NSObject
{
NSMutableArray *children;
NSMutableData *webData;
}
#property (nonatomic, retain) NSMutableArray *children;
-(void)connectionSetUp;
#end
ChildConnection.m:
#import "ChildConnection.h"
#import "ChildParser.h"
#implementation ChildConnection
#synthesize children;
- (void)connectionSetUp
{
NSString *soapMsg =
[NSString stringWithFormat:
Soap message left out due to sensitive data
];
NSURL *url = [NSURL URLWithString:#"Private"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
// Calculate the length of the post
NSString *postLength = [NSString stringWithFormat:#"%d", [soapMsg length]];
// Set the headers
[req addValue:postLength forHTTPHeaderField:#"Content-Length"];
[req addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[req addValue:#"PRIVATE" forHTTPHeaderField:#"SOAPAction"];
// Set the HTTP method and body
[req setHTTPMethod:#"POST"];
[req setHTTPBody:[soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *myConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
if(myConnection)
{
NSLog(#"Connection established");
webData = [NSMutableData data];
} else
{
NSLog(#"Connection failed");
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"didReceiveResponse");
[webData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//NSLog(#"didReceiveData");
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", [error localizedDescription]);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Finished loading");
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:webData];
//Initialize the delegate.
ChildParser *parser = [[ChildParser alloc] initXMLParser];
//Set delegate
[xmlParser setDelegate:parser];
//Start parsing the XML file.
BOOL success = [xmlParser parse];
/*
if(success)
NSLog(#"No Errors");
else
NSLog(#"Error Error Error!!!");
*/
//NSLog(#"Count: %#", [ count]);
}
#end
ChildParser.h:
#class Child;
#class ChildConnection;
#interface ChildParser : NSObject <NSXMLParserDelegate>
{
NSMutableString *currentElementValue;
Child *aChild;
ChildConnection *childConnection;
}
- (ChildParser *) initChildParser;
#end
.m:
#import "ChildParser.h"
#import "Child.h"
#import "ChildConnection.h"
#implementation ChildParser
- (ChildParser *) initChildParser {
self = [super init];
if(self)
{
childConnection = (ChildConnection *)[[UIApplication sharedApplication] delegate];
NSLog(#"Init");
}
return self;
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict
{
NSLog(#"didstart");
if([elementName isEqualToString:#"GetKidsResult"])
{
// initialize the array
if(!childConnection.children)
{
childConnection.children = [[NSMutableArray alloc] init];
}
}
else if([elementName isEqualToString:#"a:KeyValueOfintKidf4KEWLbb"])
{
if(!aChild)
{
//Initialize the child.
aChild = [[Child alloc] init];
}
}
//NSLog(#"Processing Element: %#", elementName);
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
NSLog(#"foundcharacters");
/*
if(!currentElementValue)
{
currentElementValue = [[NSMutableString alloc] initWithString:string];
}
else
{
[currentElementValue appendString:string];
}*/
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
//NSLog(#"El name: %#", elementName);
if([elementName isEqualToString:#"GetKidsResult"])
{
NSLog(#"end of xml");
return;
}
if([elementName isEqualToString:#"a:KeyValueOfintKidf4KEWLbb"])
{
//NSLog(#"Found end of child");
//[childConnection.children addObject:aChild];
//NSLog(#"added");
//int i = [childConnection.children count];
//NSLog(#"Count: %d", i);
//aChild = nil;
}
else if([elementName isEqualToString:#"a:Key"])
{
//NSLog(#"Found key: %#", currentElementValue);
//aChild.key = [currentElementValue intValue];
//NSLog(#"key: %#", aChild.key);
}
else if([elementName isEqualToString:#"b:CPR"])
{
//NSLog(#"Found cpr");
//aChild.cpr = [currentElementValue intValue];
}
else if([elementName isEqualToString:#"b:CheckedIn"])
{
//NSLog(#"Found checkedIn");
//aChild.checkedIn = [currentElementValue boolValue];
}
else if([elementName isEqualToString:#"b:FirstName"])
{
//NSLog(#"Found firstname: %#", currentElementValue);
//[aChild setValue:currentElementValue forKey:#"firstName"];
//aChild.firstName = currentElementValue;
}
else if([elementName isEqualToString:#"b:Gender"])
{
//NSLog(#"found gender");
//aChild.gender = currentElementValue;
}
else if([elementName isEqualToString:#"b:Id"])
{
//NSLog(#"found id");
aChild.idChild = [currentElementValue intValue];
}
else if([elementName isEqualToString:#"b:IsOnTour"])
{
//NSLog(#"found isontour");
//aChild.isOnTour = [currentElementValue boolValue];
}
else if([elementName isEqualToString:#"b:LastName"])
{
//NSLog(#"found lastname: %#", currentElementValue);
//aChild.lastName = currentElementValue;
}
else if([elementName isEqualToString:#"b:GroupName"])
{
//NSLog(#"found groupname");
//aChild.groupName = currentElementValue;
}
currentElementValue = nil;
}
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
NSLog(#"didEndDocument");
//NSLog(#"Number of objects: %d", [childConnection.children count]);
[[NSNotificationCenter defaultCenter] postNotificationName:#"finishedParsing" object:nil];
}
#end
UPDATE
Okay, so got a bit further... I'm now getting a SIGABRT in the class where I use the data:
#import "AllView.h"
#import "CustomCellNoSubtitle.h"
#import "DTCustomColoredAccessory.h"
#import "Child.h"
#import "ChildConnection.h"
#implementation AllView
#synthesize allChildrenTable, childView, whichGroupLabel, charIndex;
-(void)receivedData
{
NSLog(#"data update gotten");
charIndex = [[NSMutableArray alloc] init];
listOfNames = [[NSMutableArray alloc] init];
for(int i=0; i<[childConnection.children count]-1; i++)
{
// get the person
Child *aChild = [childConnection.children objectAtIndex:i];
// get both first and last name and join them
NSString *joinName = [NSString stringWithFormat:#"%# %#", aChild.firstName, aChild.lastName];
// save the full name to an array of all the names
[listOfNames addObject:joinName];
// get the first letter of the first name
NSString *firstLetter = [aChild.firstName substringToIndex:1];
NSLog(#"first letter: %#", firstLetter);
// if the index doesn't contain the letter
if(![charIndex containsObject:firstLetter])
{
// then add it to the index
NSLog(#"adding: %#", firstLetter);
[charIndex addObject:firstLetter];
}
}
[allChildrenTable reloadData];
}
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Deselect the row, so it's clear when the user returns
[allChildrenTable deselectRowAtIndexPath:indexPath animated:YES];
if(self.childView == nil)
{
ChildView *cView = [[ChildView alloc] initWithNibName:#"ChildView" bundle:[NSBundle mainBundle]];
self.childView = cView;
}
[self.navigationController pushViewController:childView animated:YES];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// set the number of sections in the table to match the number of first letters
return [charIndex count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
// set the section title to the matching letter
return [charIndex objectAtIndex:section];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// get the letter in each section
NSString *alphabet = [charIndex objectAtIndex:section];
// get the names beginning with the letter
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF beginswith[c] %#", alphabet];
NSArray *names = [listOfNames filteredArrayUsingPredicate:predicate];
return [names count];
}
// set up an index
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
return charIndex;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
CustomCellNoSubtitle *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
//cell = [[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier];
//cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell = [[CustomCellNoSubtitle alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
//cell.frame = CGRectZero;
}
/*
//---get the letter in the current section---
NSString *alphabet = [charIndex objectAtIndex:[indexPath section]];
//---get all states beginning with the letter---
NSPredicate *predicate =
[NSPredicate predicateWithFormat:#"SELF beginswith[c] %#", alphabet];
NSArray *names = [listOfNames filteredArrayUsingPredicate:predicate];
if ([names count]>0) {
//---extract the relevant state from the states object---
NSString *cellValue = [names objectAtIndex:indexPath.row];
cell.primaryLabel.text = cellValue;
}
cell.myImageView.image = [UIImage imageNamed:#"kidblank.png"];*/
return cell;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
//childConnection = (ChildConnection *)[[UIApplication sharedApplication] delegate];
childConnection =[[ChildConnection alloc] init];
[allChildrenTable reloadData];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Set up a connection to the server to fetch the list of children
ChildConnection *childConnection = [[ChildConnection alloc] init];
[childConnection connectionSetUp];
// Set up a listener to receive notice when the parser is done
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(receivedData) name:#"finishedParsing" object:nil];
}
The problem looks pretty simple.
In your very first pasted function, you are assigning your app delegate to the variable childConnection.
childConnection = (ChildConnection *)[[UIApplication sharedApplication] delegate];
Surely you actually want to assign a new instance of the ChildConnection class to that property instead. Like this:
childConnection = [[ChildConnection alloc] init];
I know that Objective-C errors can sometimes be hard to make sense of, but the one you are getting is actually pretty clear:
[AppDelegate children]: unrecognised selector
So it's complaining that you are calling a method/property "children" on the app delegate. But why would you be calling anything on the app delegate if you aren't using it any more? And why would you call a method called "children" on it, when that's actually defined as a property of the ChildConnection class, not the app delegate?
Answer: because an object you thought was a ChildConnection is actually the app delegate.
UPDATE: It looks like you need to use the ChildConnection in more than one place. The easiest way to do this is to make a shared instance. Add this method to your ChildConnection class:
+ (ChildConnection *)sharedConnection
{
static ChildConnection *sharedConnection = nil;
if (sharedConnection == nil)
{
sharedConnection = [[self alloc] init];
}
return sharedConnection;
}
Now in your other classes, wherever you've used [[ChildConnection alloc] init] use [ChildConnection sharedInstance] instead.
Your right the offending piece of code is :
if(self)
{
childConnection = (ChildConnection *)[[UIApplication sharedApplication] delegate];
NSLog(#"Init");
}
And the reason why is your casting your AppDelegate to a ChildConnection Object, you can't do this because well it isn't a ChildConnection.
If you want to reference your childConnection in your AppDelegate i recommend the following:
+ (AppDelegate*)sharedDelegate;
//Implementation
+ (AppDelegate*)sharedDelegate {
return (AppDelegate*)[[UIApplication sharedApplication] delegate];
}
So this way you reference your childConnection like so:
[AppDelegate sharedDelegate].childConnection;
If you need data the moment the App starts initialise the childConnection in:
application:didFinishLaunchingWithOptions:

Resources