How to keep the checkmark in a UITableView after the view disappears - iphone

I have a uitableview that's displaying multiple selections with a custom checkmark. When selected the rows value is save using NSUserDefaults. The problem is that despite the values being saved the checkmarks disappear from the table cell rows. I can't figure out why.
thanks for any help, I'm really stuck on this.
Here's the .h code:
#interface CategoriesViewController : UITableViewController {
NSString *selectedCategoryTableString;
NSString *jsonStringCategory;
int prev;
}
// arForTable array will hold the JSON results from the api
#property (nonatomic, retain) NSArray *arForTable;
#property (nonatomic, retain) NSMutableArray *arForIPs;
#property (nonatomic, retain) NSMutableArray *categorySelected;
#property (nonatomic, retain) NSString *jsonStringCategory;
#property(nonatomic, retain) UIView *accessoryView;
#end
and the .m code:
#implementation CategoriesViewController
#synthesize jsonStringCategory;
#synthesize arForTable = _arForTable;
#synthesize arForIPs = _arForIPs;
- (void)viewDidLoad
{
[super viewDidLoad];
self.arForIPs=[NSMutableArray array];
self.categorySelected = [[NSMutableArray alloc] init];
[self reloadMain];
self.tableView.allowsMultipleSelection = YES;
}
-(void) reloadMain {
jsonString = #"http:///******";
// Download the JSON
NSString *jsonString = [NSString
stringWithContentsOfURL:[NSURL URLWithString:jsonString]
encoding:NSStringEncodingConversionAllowLossy|NSUTF8StringEncoding
error:nil];
NSMutableArray *itemsTMP = [[NSMutableArray alloc] init];
// Create parser
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *results = [parser objectWithString:jsonString error:nil];
itemsTMP = [results objectForKey:#"results"];
self.arForTable = [itemsTMP copy];
[self.tableView reloadData];
}
#pragma mark - Table view data source
- (int)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.arForTable count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
[cell.textLabel setFont:[UIFont fontWithName: #"Asap-Bold" size: 14.0f]];
[cell.detailTextLabel setFont:[UIFont fontWithName: #"Asap-Bold" size: 14.0f]];
cell.accessoryView.hidden = NO;
}
UIImageView *cellAccessoryImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"icon-tick.png"]] ;
UIImageView *cellAccessoryNoneImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#""]] ;
if([self.arForIPs containsObject:indexPath]){
cell.accessoryView = cellAccessoryImageView;
} else {
cell.accessoryView = cellAccessoryNoneImageView;
}
// Get item from tableData
NSDictionary *item = (NSDictionary *)[_arForTable objectAtIndex:indexPath.row];
// encoding fix
NSString *utf8StringTitle = [item objectForKey:#"name"];
NSString *correctStringTitle = [NSString stringWithCString:[utf8StringTitle cStringUsingEncoding:NSISOLatin1StringEncoding] encoding:NSUTF8StringEncoding];
cell.textLabel.text = [correctStringTitle capitalizedString];
NSNumber *num = [item objectForKey:#"id"];
cell.detailTextLabel.text = [num stringValue];
cell.detailTextLabel.hidden = YES;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if([self.arForIPs containsObject:indexPath]){
[self.arForIPs removeObject:indexPath];
[self.categorySelected removeObject:[[self.arForTable objectAtIndex:indexPath.row] objectForKey:#"id"]];
} else {
[self.arForIPs addObject:indexPath];
[self.categorySelected addObject:[[self.arForTable objectAtIndex:indexPath.row] objectForKey:#"id"]];
NSLog(#"%# categorySelected",self.categorySelected);
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSLog(#"%# defaults categorySelected",[defaults arrayForKey:#"selectedCategoryTableString"]);
NSString *string = [self.categorySelected componentsJoinedByString:#","];
[defaults setObject:string forKey:#"selectedCategoryTableString"];
NSLog(#"%# STRING",string);
}
[tableView reloadData];
}
-(void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:NO];
[self.navigationController setNavigationBarHidden:YES animated:NO];
self.navigationController.toolbarHidden = YES;
}

First of all your code has lots of memory leaks, please do use the static analyzer and/or instruments to fix them, few for them are pretty obvious like you initialized the SBJSON parser and did not release it, itemsTMP is another.
I have rewritten your code to be much more efficient and memory friendly:
#interface CategoriesViewController : UITableViewController
{
NSArray *_items;
NSMutableArray *_selectedItems;
UIImageView *cellAccessoryImageView;
}
#end
#implementation CategoriesViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_selectedItems = [NSMutableArray new];
cellAccessoryImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"icon-tick.png"]] ;
[self reloadMain];
self.tableView.allowsMultipleSelection = YES;
}
- (void)reloadMain
{
NSString *jsonString = #"http:///******";
// Download the JSON
jsonString = [NSString
stringWithContentsOfURL:[NSURL URLWithString:jsonString]
encoding:NSStringEncodingConversionAllowLossy|NSUTF8StringEncoding
error:nil];
// Create parser
SBJSON *parser = [SBJSON new];
NSDictionary *results = [parser objectWithString:jsonString error:nil];
if (_items) [_items release];
_items = [[results objectForKey:#"results"] copy];
[parser release];
[self.tableView reloadData];
}
#pragma mark - Table view data source
- (int)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_items count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
[cell.textLabel setFont:[UIFont fontWithName: #"Asap-Bold" size: 14.0f]];
[cell.detailTextLabel setFont:[UIFont fontWithName: #"Asap-Bold" size: 14.0f]];
cell.accessoryView.hidden = NO;
}
NSDictionary *item = [_items objectAtIndex:indexPath.row];
if ([_selectedItems containsObject:item])
{
// preloaded image will help you have smoother scrolling
cell.accessoryView = cellAccessoryImageView;
}
else
{
cell.accessoryView = nil;
cell.accessoryType = UITableViewCellAccessoryNone;
}
// Get item from tableData
cell.textLabel.text = [[NSString stringWithCString:[[item objectForKey:#"name"] cStringUsingEncoding:NSISOLatin1StringEncoding] encoding:NSUTF8StringEncoding] capitalizedString];
cell.detailTextLabel.text = [[item objectForKey:#"id"] stringValue];
cell.detailTextLabel.hidden = YES;
item = nil;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSDictionary *item = [_items objectAtIndex:indexPath.row];
if ([_selectedItems containsObject:item])
{
[_selectedItems removeObject:item];
}
else
{
[_selectedItems addObject:item];
}
item = nil;
[tableView reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
- (void)dealloc
{
[_selectedItems release];
[cellAccessoryImageView release];
[super dealloc];
}
#end

Since in your table there is only one section. Try this approach and this will help you certainly.
In - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath write following code;
if([self.arForIPs containsObject:[NSNumber numberWithInt:indexPath.row]]){
cell.accessoryView = cellAccessoryImageView;
} else {
cell.accessoryView = cellAccessoryNoneImageView;
}
And in - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath write code as below,
if([self.arForIPs containsObject:[NSNumber numberWithInt:indexPath.row]]){
[self.arForIPs removeObject:[NSNumber numberWithInt:indexPath.row]];
} else {
[self.arForIPs addObject:[NSNumber numberWithInt:indexPath.row]]
}

Related

Xcode live news feed with multiple accounts or user

Im new to xcode.
and Im creating this facebook, twitter, instagram and youtube news feed in a tableview
at first Im trying this facebook to load multiple json
#import "ViewController.h"
#import "DetailViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#define kQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#define kJSONUrl [NSURL URLWithString:#"https://www.facebook.com/feeds/page.php?id=1387524391527078&format=json"]
#define kJSONUrl1 [NSURL URLWithString:#"https://www.facebook.com/feeds/page.php?id=196934133652011&format=json"]
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#interface ViewController ()
#end
#implementation ViewController
#synthesize jsonTitles,table,jsonContent;
-(void)loadJSON:(NSData *)responseData {
NSError *error;
NSArray *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSArray *array = [json valueForKey:#"entries"];
for (int i = 0; i < array.count; i++) {
NSArray *entry = [array objectAtIndex:i];
NSString *title = [entry valueForKey:#"title"];
NSString *content = [entry valueForKey:#"content"];
[jsonTitles addObject:title];
[jsonContent addObject:content];
}
[self.table reloadData];
}
- (void)viewDidLoad
{
self.table.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"background.png"]];
jsonTitles = [[NSMutableArray alloc]init];
jsonContent = [[NSMutableArray alloc]init];
dispatch_async(kQueue, ^{
NSData *data = [NSData dataWithContentsOfURL:kJSONUrl];
[self performSelectorOnMainThread:#selector(loadJSON:) withObject:data waitUntilDone:YES];
NSData *data1 = [NSData dataWithContentsOfURL:kJSONUrl1];
[self performSelectorOnMainThread:#selector(loadJSON:) withObject:data1 waitUntilDone:YES];
});
[super viewDidLoad];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 40;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [jsonTitles count];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self performSegueWithIdentifier:#"detailSegue" sender:nil];
// NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:#"detailSegue" ascending:YES];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"detailSegue"]) {
DetailViewController *detail = segue.destinationViewController;
NSIndexPath *path = [self.table indexPathForSelectedRow];
detail.titleText = [jsonTitles objectAtIndex:path.row];
detail.contentText = [jsonContent objectAtIndex:path.row];
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *tableCellID = #"tableCellID";
// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tableCellID];
UITableViewCell *cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:tableCellID];
NSString *myurl = #"http://graph.facebook.com/idoltap/picture";
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:myurl]];
UIImage *myimage = [[UIImage alloc] initWithData:imageData];
cell.imageView.image = myimage;
// cell.imageView.image = [UIImage imageNamed:#"background.png"];
cell.textLabel.text = #"iDOLTap";
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableCellID];
}
cell.detailTextLabel.text = [jsonTitles objectAtIndex:indexPath.row];
if ([cell.detailTextLabel.text isEqual: #" "]) {
cell.detailTextLabel.text = [jsonContent objectAtIndex:indexPath.row];
}
return cell;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Is my pattern correct?
I dont know how I can load the right profile picture for each json/user and sort it by its published date.
I just want some help to fix this one in the right way.

UITableView Crashes when scrolling and [reloadData]

I'm creating a app using theos (jailbreak) and I have created a UITableView in the loadView method in my RootViewController.mm file:
- (void)loadView {
self.view = [[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
self.view.backgroundColor = [UIColor redColor];
NSError * error;
NSArray * directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:#"/var/mobile/Library/BannerImage" error:&error];
countries = [NSDictionary dictionaryWithObject:directoryContents forKey:#"Themes"];
mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 480) style:UITableViewStyleGrouped];
[mainTableView setDataSource:self];
[mainTableView setDelegate:self];
[self.view addSubview:mainTableView];
}
And the rest of my code:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [countries count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [[countries allKeys] objectAtIndex:section];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSString *continent = [self tableView:tableView titleForHeaderInSection:section];
return [[countries valueForKey:continent] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
NSString *continent = [self tableView:tableView titleForHeaderInSection:indexPath.section];
NSString *country = [[countries valueForKey:continent] objectAtIndex:indexPath.row];
cell.textLabel.text = country;
cell.accessoryType = UITableViewCellAccessoryNone;
if([self.checkedIndexPath isEqual:indexPath])
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *object = [tableView cellForRowAtIndexPath:indexPath];
[object setSelected:NO animated:YES];
NSString *selectedTheme = [[object textLabel] text];
NSDictionary *plistFile = [NSDictionary dictionaryWithObject:selectedTheme forKey:#"CurrentTheme"];
[plistFile writeToFile:#"/Applications/BannerImage.app/CurrentTheme.plist" atomically:YES];
if(self.checkedIndexPath)
{
UITableViewCell* uncheckCell = [tableView
cellForRowAtIndexPath:checkedIndexPath];
uncheckCell.accessoryType = UITableViewCellAccessoryNone;
}
UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
self.checkedIndexPath = indexPath;
}
It crashes when I scroll up and try to scroll back down and it crashes when [mainTableView reloadData] is called. How can I fix this?
Crash Log
I found out that I needed to retain the Dictionary because it was being released. So instead of
NSDictionary *countries;
change to this
#property(nonatomic, retain) NSDictionary *countries;
and
#synthesize countries;
in your .mm file and use
self.countries = [NSDictionary dictionaryWithObject:directoryContents forKey:#"Themes"];
instead of
countries = [NSDictionary dictionaryWithObject:directoryContents forKey:#"Themes"];
Hi, Please check there if is any data in countries and "continent" value key is presented or not in dic before this line
NSString *country = [[countries valueForKey:continent] objectAtIndex:indexPath.row];

Second view in UITableView will not display parsed data from JSON

I have a parsed data from JSON file. It works like a charm in the first view of my UITableView. However, it displays a blank second view when I tap on an item.
MasterView.h
#interface MasterViewController : UITableViewController
{
NSArray *json;
}
#property (nonatomic, retain) NSArray *json;
#end
MasterView.m
#import "MasterViewController.h"
#import "InformationViewController.h"
#interface MasterViewController ()
#end
#implementation MasterViewController
#synthesize json;
- (void)viewDidLoad
{
[super viewDidLoad];
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://j4hm.t15.org/ios/console.php"]];
[self performSelectorOnMainThread: #selector(fetchedData:) withObject: jsonData waitUntilDone: YES];
}
- (void)fetchedData:(NSData *)responseData
{
NSError *error;
self.json = [NSJSONSerialization JSONObjectWithData: responseData options: kNilOptions error: &error];
NSLog(#"String is %#", self.json);
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [json count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
cell.textLabel.text = [[json objectAtIndex: indexPath.row] objectForKey: #"Console"];
[cell setAccessoryType: UITableViewCellAccessoryDisclosureIndicator];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
InformationViewController *informationViewController = [[InformationViewController alloc] initWithStyle:UITableViewStylePlain];
informationViewController.title = [[json objectAtIndex: indexPath.row] objectForKey: #"Console"];
informationViewController.Information = [[json objectAtIndex: indexPath.row] objectForKey: #"Model"];
NSLog(#"String is %#", informationViewController.Information);
[self.navigationController pushViewController: informationViewController animated:YES];
}
InformationView.h
#interface InformationViewController : UITableViewController
#property (nonatomic, strong) NSArray * Information;
#end
InformationView.m
#interface InformationViewController ()
#end
#implementation InformationViewController
#synthesize Information;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
cell.textLabel.text = [[Information objectAtIndex: indexPath.row] objectForKey: #"Model"];
[cell setAccessoryType: UITableViewCellAccessoryDisclosureIndicator];
return cell;
}
Here i Posted Another Answer Just Because i don't want to Generate Confusion.
The Project Code : http://www.cogzentappz.com/demo/iostutorial/TestJson.zip
instead of passing the Selected Value, Pass the Whole Array through NSUsedDefaults And Retrive them Using Following Code.
- (void)fetchedData:(NSData *)responseData
{
NSError *error;
self.json = [NSJSONSerialization JSONObjectWithData: responseData options: kNilOptions error: &error];
NSLog(#"String is %#", self.json);
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *arrayObj = [[NSMutableArray alloc] init];
for(int i = 0 ; i<[self.json count] ; i++) {
[arrayObj addObject:[json objectAtIndex:i]]];
}
[standardDefaults setObject:arrayObj forKey:#"longArray"];
[arrayObj release];
}
In the Next View you can Retrive the data Using the Below method.
in ViewDidLoad of informationViewcontroller use This
//reading
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
NSArray *arrayObj = [standardDefaults objectForKey:#"longArray"];
for(int i = 0 ; i<[arrayObj count] ; i++) {
NSLog(#"String is %#",[arrayObj objectAtIndex:i]);
}
As per Your Link The Json Output is like Below :
NSArray-->NSDictionary-->NSArray-->NSDictionary-->NSArray-->NSDictionary
Go to the link : http://json.bloople.net and Post all your json output and Hit enter.
So you have to get the values According to that format.
for(int i = 0 ; i<[self.json count] ; i++) {
NSArray *info_Array=[[self.json objectAtIndex:i ]valueForKey:#"Information"];
NSLog(#"info_Array is %#", info_Array);
for(int j = 0 ; j<[info_Array count] ; j++)
{
NSLog(#"Model is %#", [[info_Array objectAtIndex:j ]valueForKey:#"Model"]);
NSArray *title_Array=[[info_Array objectAtIndex:j ]valueForKey:#"Title"];
for(int k = 0 ; k<[title_Array count] ; k++)
{
NSLog(#"Game is %#", [[title_Array objectAtIndex:k ]valueForKey:#"Game"]);
NSLog(#"Publisher is %#", [[title_Array objectAtIndex:k ]valueForKey:#"Publisher"]);
}
}
NSString *Console_string= [[dataArray objectAtIndex:i ]valueForKey:#"Console"];
NSLog(#"String is %#", Console_string);
}
NSString *Console_string= [[self.Json objectAtIndex:i ]valueForKey:#"Console"];
NSLog(#"String is %#", Console_string);
}
I think you have to reloadData after you fetch your data. Right now, you specify that the NSArrray *json is empty, since the count returns 0. Thus, you prohibit the table view from being filled. Call [tableView reloadData]; after you fetch your data.
Change your code of MaterView.m with this
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
InformationViewController *informationViewController = [[InformationViewController alloc] initWithStyle:UITableViewStylePlain];
informationViewController.title = [[json objectAtIndex: indexPath.row] objectForKey: #"Console"];
informationViewController.Information = [[json objectAtIndex: indexPath.row] objectForKey: #"Model"];
NSLog(#"String is %#", informationViewController.Information);
[self.navigationController pushViewController: informationViewController animated:YES];
}
Hope it helps you...

TableView not getting hidden in didSelectRowAtIndexPath in xcode?

I m fairly new to objective-C and implementing the concept of autocomplete feature for a UItextField.I can do it appropriately .but when I select a particular cell then that cell's text should be displayed in UITextField and correspondingly tableView must be hidden.But Im unable to hide a UITableView after selecting a cell..Where I m going wrong?
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring {
NSURL *urlString= [NSString stringWithFormat:#"http://179.87.89.90/services/Service.svc/GetCities/?p=%#&k=%#",substring,txtId.text];
NSURL *jsonUrl =[NSURL URLWithString:urlString];
NSString *jsonStr = [[NSString alloc] initWithContentsOfURL:jsonUrl];
parser = [[NSXMLParser alloc] initWithContentsOfURL:jsonUrl];
currentHTMLElement=#"3";
[parser setDelegate:self];
[parser setShouldProcessNamespaces:NO];
[parser setShouldReportNamespacePrefixes:NO];
[parser setShouldResolveExternalEntities:NO];
[parser parse];
[parser release];
NSLog(#"%#",arr2);
if([arr2 count]!=0)
{
self.autocompleteUrls = [[NSMutableArray alloc] init];
autocompleteTableView = [[UITableView alloc] initWithFrame:CGRectMake(88, 447, 200, 120) style:UITableViewStyleGrouped];
autocompleteTableView.delegate = self;
autocompleteTableView.dataSource = self;
autocompleteTableView.scrollEnabled = YES;
// autocompleteTableView.hidden = YES;
[self.view addSubview:autocompleteTableView];
[autocompleteUrls removeAllObjects];
for(int i=0;i<[arr2 count];i++)
{
NSString *curString = [[arr2 objectAtIndex:i] valueForKey:#"Name"];
NSRange substringRange = [curString rangeOfString:substring];
if (substringRange.location == 0)
[autocompleteUrls addObject:curString];
}
[autocompleteTableView reloadData];
}
else
{
autocompleteTableView.delegate=nil;
autocompleteTableView.dataSource=nil;
autocompleteTableView.hidden = YES;
}
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if( textField == txtcity)
{
autocompleteTableView.hidden = NO;
NSString *substring = [NSString stringWithString:textField.text];
substring = [substring stringByReplacingCharactersInRange:range withString:string];
[self searchAutocompleteEntriesWithSubstring:substring];
return YES;
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger) section {
return autocompleteUrls.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = nil;
static NSString *AutoCompleteRowIdentifier = #"AutoCompleteRowIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:AutoCompleteRowIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:AutoCompleteRowIdentifier] autorelease];
}
cell.textLabel.text = [autocompleteUrls objectAtIndex:indexPath.row];
cell.textLabel.font=[UIFont boldSystemFontOfSize:12];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
txtcity.text = selectedCell.textLabel.text;
[autocompleteUrls removeAllObjects];
[self.autocompleteTableView setHidden:YES];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
txtcity.text = selectedCell.textLabel.text;
[autocompleteUrls removeAllObjects];
autocompleteTableView.hidden=YES;
}
How can I hide autocompleteTableView after selecting a row ?
Any help would be appreciated..
The issue is with the if condition, when the if is evaluated true then again the autocompleteTableView is again allocated and added to self.view. It'll be placed over the previous tableView and youare losing the reference of previous tableView. If you call autocompleteTableView.hidden = YES. Last added tableView will be hidden. But previously added tableViews will be there.
Just change the if block like:
if([arr2 count]!=0)
{
self.autocompleteUrls = [[NSMutableArray alloc] init];
if(autocompleteTableView)
[autocompleteTableView removeFromSuperView];
autocompleteTableView = [[UITableView alloc] initWithFrame:CGRectMake(88, 447, 200, 120) style:UITableViewStyleGrouped];
autocompleteTableView.delegate = self;
autocompleteTableView.dataSource = self;
autocompleteTableView.scrollEnabled = YES;
// autocompleteTableView.hidden = YES;
[self.view addSubview:autocompleteTableView];
for(int i=0;i<[arr2 count];i++)
{
NSString *curString = [[arr2 objectAtIndex:i] valueForKey:#"Name"];
NSRange substringRange = [curString rangeOfString:substring];
if (substringRange.location == 0)
[autocompleteUrls addObject:curString];
}
[autocompleteTableView reloadData];
}
#Arizah - please try making a fresh app to test the UItableview & UItextField delegate methods. It might be that somewhere --
autocompleteTableView.delegate=nil;
autocompleteTableView.dataSource=nil;
gets called due to which further no delegate method like :
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
WILL NOT BE CALLED. TRY AVOIDING THIS CODE.
Also the statement: self.autocompleteUrls = [[NSMutableArray alloc] init];
is technically incorrect since a retain property needs no allocation. Instead you can use:
NSMutableArray *theArray= [[NSMutableArray alloc] init];
self.autocompleteUrls = theArray;
[theArray release];
did you try:
[self.tableView setHidden:YES];

UIPickerView in Detailview with .PLIST

I've searched the web + stackoverflow for a solution.
I've an UITableView with information from a .plist file. The plist file have childs. Like the image.
plist http://www.afbeeldingenuploaden.nl/uploads/648899Schermafbeelding%202011-06-12%20om%2009.50.28.png
When i go to DetailView it will display information out of an UIPickerView that's included in the view. I want to display information from the child in the pickerview, the last level. Like the image.
plist1 http://www.afbeeldingenuploaden.nl/uploads/740501Schermafbeelding%202011-06-12%20om%2012.03.40.png
The problem is that i can't reach the last level from the plist in the UIPickerview with my code.
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
NSDictionary *dictionary = [tableDataSource objectAtIndex:row];
return [dictionary objectForKey:#"days"];
}
I use in my tableview for the detailview to reach the last level of the plist.
NSString currentLevel
Can anyone help me out with this, i'm stuck.
As I read the plist, it has an array of dictionaries first of which has a dictionary as one of its values at the second array level. Based on that, your method should be,
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
NSDictionary *dictionary = [tableDataSource objectAtIndex:row];
return [[dictionary objectForKey:#"New item"] objectForKey:#"days"];
}
This will work for the plist in the image. However if more members are added they should adhere to the same structure.
- (void)viewDidLoad {
[super viewDidLoad];
NSString *Path = [[NSBundle mainBundle] bundlePath];
NSString *DataPath = [Path stringByAppendingPathComponent:#"Diyet.plist"];
NSDictionary *tempDict = [[NSDictionary alloc] initWithContentsOfFile:DataPath];
self.data = tempDict;
[tempDict release];
NSArray *tempArray = [[NSArray alloc] init];
self.tableDataSource = tempArray;
[tempArray release];
self.tableDataSource = [data objectForKey:#"Bitki"];
pickerView.delegate = self;
pickerView.dataSource = self;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
// Configure the cell.
cell.textLabel.text = [[tableDataSource objectAtIndex:indexPath.row] objectForKey:#"name"];
cell.textLabel.numberOfLines = 2;
cell.textLabel.font = [UIFont boldSystemFontOfSize:16];
tableView.scrollEnabled = NO;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *dictionary = [tableDataSource objectAtIndex:indexPath.row];
NSArray *modelle = [dictionary objectForKey:#"DETAIL"];
if([modelle count] == 0) {
DetailController *dvController = [[DetailController alloc] initWithNibName:#"DetailController" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:dvController animated:YES];
dvController.names.text = [dictionary objectForKey:#"name"];
} else {
BootViewController *rvController = [[BootViewController alloc] initWithNibName:#"BootViewController" bundle:[NSBundle mainBundle]];
rvController.currentLevel += 1;
rvController.currentTitle = [dictionary objectForKey:#"name"];
[self.navigationController pushViewController:rvController animated:YES];
rvController.tableDataSource = modelle;
[rvController release];
}
}