I know this question has been asked before but mine is different. My app has an add button and edit button that deletes/adds table views. I want every cell that is created by the user to go to the same view. I've been looking everywhere for the code but I can't find it. BTW the ____ is just a placeholder. The table coding is in the app delegate and I have a second view controller for the view that is loaded when a row is clicked.
AppDelegate.h
#interface _____AppDelegate : NSObject <UIApplicationDelegate> {
CustomCellViewController *customCellViewController;
IBOutlet UIWindow *window;
IBOutlet UITableViewCell *customCell;
NSMutableArray *data;
IBOutlet UITableView *mainTableView;
IBOutlet UINavigationItem *navItem;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet UINavigationController *navController;
#property (nonatomic, retain) CustomCellViewController *customCellViewController;
- (IBAction)addRowToTableView;
- (IBAction)editTable;
- (NSString *)dataFilePath;
#end
AppDelegate.m
#import "______AppDelegate.h"
#implementation ______AppDelegate;
#synthesize window;
#synthesize navController=_navController;
#synthesize customCellViewController;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
NSArray *archivedArray = [NSKeyedUnarchiver unarchiveObjectWithFile:[self dataFilePath]];
if (archivedArray == nil) {
data = [[NSMutableArray alloc] init];
} else {
data = [[NSMutableArray alloc] initWithArray:archivedArray];
}
// Override point for customization after application launch
self.window.rootViewController = self.navController;
[self.window makeKeyAndVisible];
return YES;
}
- (IBAction)addRowToTableView {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"New Product" message:#"What is the name of your product?" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok", nil];
[alert addTextFieldWithValue:#"" label:#"Name of product..."];
UITextField *tf = [alert textFieldAtIndex:0];
tf.clearButtonMode = UITextFieldViewModeWhileEditing;
tf.keyboardType = UIKeyboardTypeURL;
tf.keyboardAppearance = UIKeyboardAppearanceAlert;
tf.autocapitalizationType = UITextAutocapitalizationTypeNone;
tf.autocorrectionType = UITextAutocorrectionTypeNo;
[alert show];
}
-(void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 1) {
UITextField *tf = [alert textFieldAtIndex:0];
[data addObject:tf.text];
[self saveData];
[mainTableView reloadData];
}
}
- (IBAction)editTable {
UIBarButtonItem *leftItem;
[mainTableView setEditing:!mainTableView.editing animated:YES];
if (mainTableView.editing) {
leftItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(editTable)];
} else {
leftItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:#selector(editTable)];
}
navItem.rightBarButtonItem = leftItem;
[self saveData];
[mainTableView reloadData];
}
- (IBAction)endText {
}
- (NSInteger)numberOfSectionInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [data count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifer = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:"Cell"] autorelease];
}
cell.textLabel.text = [data objectAtIndex:indexPath.row];
return cell;
}
- (NSString *)dataFilePath {
NSString *dataFilePath;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
dataFilePath = [[documentDirectory stringByAppendingPathComponent:#"applicationData.plist"] retain];
return dataFilePath;
}
- (void)saveData {
[NSKeyedArchiver archiveRootObject:[data copy] toFile:[self dataFilePath]];
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
[data removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath
toIndexPath:(NSIndexPath *)toIndexPath {
NSString *item = [[data objectAtIndex:fromIndexPath.row] retain];
[data removeObject:item];
[data insertObject:item atIndex:toIndexPath.row];
[item release];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)dealloc {
[window release];
[_navController release];
[customCellViewController release];
[super dealloc];
}
#end
I don't mean to be harsh, but you have a lot of basics to learn. ARC will make your life much easier and your code better, by eliminating the need to manually manage memory (for the most part). You can enable it when you first start a project. You should.
Why is an App Delegate managing a table view? No, no no. The app delegate is supposed to respond to system-level events, not run your whole application. You need a separate view controller. Find some tutorials around the web and see how a basic app using a table view is structured. There are many. My favorites are on raywenderlich.com
Related
I have in my .h file:
#import <UIKit/UIKit.h>
#import "SQLClient.h"
#interface mgrViewController : UIViewController <UITableViewDelegate, UITableViewDataSource,
SQLClientDelegate>{
NSMutableArray *pajaros;
}
#property (weak, nonatomic) IBOutlet UITableView *miTabla;
#property (nonatomic, retain)NSMutableArray *pajaros;
#end
And in my .m file:
#import "mgrViewController.h"
#import "Vista2.h"
#import "SQLClient.h"
#interface mgrViewController ()
#end
#implementation mgrViewController
#synthesize miTabla;
#synthesize pajaros;
- (void)viewDidLoad
{
[super viewDidLoad];
SQLClient* client = [SQLClient sharedInstance];
client.delegate = self;
[client connect:#"xxx.xxx.xxx.xxx:xxxx" username:#"xxxxxxxxxxx" password:#"xxxxxxxxxxxx" database:#"xxxxxxxxxxx" completion:^(BOOL success) {
if (success)
{
pajaros =[[NSMutableArray alloc]init];
[client execute:#"SELECT field FROM table WHERE field='xxxxxxxxx'" completion:^(NSArray* results) {
NSMutableString* resulta = [[NSMutableString alloc] init];
for (NSArray* table in results)
for (NSDictionary* row in table)
for (NSString* column in row){
//[results appendFormat:#"\n%# = %#", column, row[column]];
[resulta appendFormat:#"\n%#", row[column]];
[pajaros addObject:resulta];
}
[client disconnect];
}];
}
}];
self.miTabla.delegate = self;
self.miTabla.dataSource = self;
}
#pragma mark - SQLClientDelegate
- (void)error:(NSString*)error code:(int)code severity:(int)severity
{
NSLog(#"Error #%d: %# (Severity %d)", code, error, severity);
[[[UIAlertView alloc] initWithTitle:#"Error" message:error delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil] show];
}
- (void)message:(NSString*)message
{
NSLog(#"Message: %#", message);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return pajaros.count;
}
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"celdaPajaros";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// elementos que contienen cada celda con sus tags
UILabel *labelTitulo = (UILabel *) [cell viewWithTag:10];
if(cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
labelTitulo.text = [pajaros objectAtIndex:indexPath.row];
return cell;
}
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 70.f;
}
#end
If I add a count for my NSMutableArray pajaros after the line of code [pajaros addObject:resulta];and I print that count, the result is 1, because my conditional where is for select a data. But if put a count in other part of my code, the result is 0.
My question is how I retain the data in my NSMutableArray for use in:
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return pajaros.count;
}
and in:
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"celdaPajaros";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// elementos que contienen cada celda con sus tags
UILabel *labelTitulo = (UILabel *) [cell viewWithTag:10];
if(cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
labelTitulo.text = [pajaros objectAtIndex:indexPath.row];
return cell;
}
?
Thanks for the help, I'm new in Objective-C.
If I initialize pajaros with a data in:
- (void)viewDidLoad
{
[super viewDidLoad];
pajaros = [NSMutableArray arrayWithObjects:#"Bird1", nil];
self.miTabla.delegate = self;
self.miTabla.dataSource = self;
}
And run my app, the labelTitulo show me Bird1. My second question is: why when I add data to my NSMutableArray pajaros from a Data Base and run my app, it's show me nothing?
Thanks.
When using properties, it's best to include self.. Try self.pajaros = [[NSMutableArray alloc]init]; and likewise in the other places where you just use pajaros.
I have in my .h file:
#import <UIKit/UIKit.h>
#import "SQLClient.h"
#interface mgrViewController : UIViewController <UITableViewDelegate, UITableViewDataSource,
SQLClientDelegate>{
NSMutableArray *pajaros;
}
#property (weak, nonatomic) IBOutlet UITableView *miTabla;
#property (nonatomic, retain)NSMutableArray *pajaros;
#end
And in my .m file:
#import "mgrViewController.h"
#import "Vista2.h"
#import "SQLClient.h"
#interface mgrViewController ()
#end
#implementation mgrViewController
#synthesize miTabla;
#synthesize pajaros;
- (void)viewDidLoad
{
[super viewDidLoad];
SQLClient* client = [SQLClient sharedInstance];
client.delegate = self;
[client connect:#"xxx.xxx.xxx.xxx:xxxx" username:#"xxxxxxxxxxx" password:#"xxxxxxxxxxxx" database:#"xxxxxxxxxxx" completion:^(BOOL success) {
if (success)
{
pajaros =[[NSMutableArray alloc]init];
[client execute:#"SELECT field FROM table WHERE field='xxxxxxxxx'" completion:^(NSArray* results) {
NSMutableString* resulta = [[NSMutableString alloc] init];
for (NSArray* table in results)
for (NSDictionary* row in table)
for (NSString* column in row){
//[results appendFormat:#"\n%# = %#", column, row[column]];
[resulta appendFormat:#"\n%#", row[column]];
[pajaros addObject:resulta];
}
[client disconnect];
}];
}
}];
self.miTabla.delegate = self;
self.miTabla.dataSource = self;
}
#pragma mark - SQLClientDelegate
- (void)error:(NSString*)error code:(int)code severity:(int)severity
{
NSLog(#"Error #%d: %# (Severity %d)", code, error, severity);
[[[UIAlertView alloc] initWithTitle:#"Error" message:error delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil] show];
}
- (void)message:(NSString*)message
{
NSLog(#"Message: %#", message);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return pajaros.count;
}
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"celdaPajaros";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// elementos que contienen cada celda con sus tags
UILabel *labelTitulo = (UILabel *) [cell viewWithTag:10];
if(cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
labelTitulo.text = [pajaros objectAtIndex:indexPath.row];
return cell;
}
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 70.f;
}
#end
I added elements to NSMutableArray pajaros in -(void)viewDidLoad{}, and my question is, how I can use my NSMutableArray pajaros in -(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath?.
Thanks :)
If I use count on my NSMutable Array and print that number, the result is 1 (because I selected only A data), but only if I use:
...
[pajaros addObject:resulta];
}
NSInteger num = pajaros.count;
NSString *inStr = [NSString stringWithFormat: #"%ld", (long)num];
self.textView.text = inStr;
[client disconnect];
}];
...
But if I perform that count in another part of my .m file show me 0, my next questions becomes why my NSMutableArray contains only the data in:
...
[pajaros addObject:resulta];
}
[client disconnect];
}];
...
?
Thanks for the help!
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//code here to dequecell
NSString *cellIdentifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
cell.textLabel.text = [pajaraos objectAtIndex:indexPath.row];
}
return cell;
}
Am having protocol errors in AllListsViewController.m, but can't figure out why. Also have some other errors which I have commented out.
AllListsViewController.m
#import "AllListsViewController.h"
#import "ChecklistViewController.h"
#import "Checklist.h"
#import "ChecklistItem.h"
#interface AllListsViewController ()
#end
#implementation AllListsViewController
/* Method 'listDetailViewController:didFinishAddingChecklist' in protocol not implemented
Method 'listDetailViewController:didFinishEditingChecklist' in protocol not implemented
Method 'listDetailViewControllerDidCancel:' in protocol not implemented
*/
{
NSMutableArray *_lists;
}
-(NSString *)documentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
return documentsDirectory;
}
-(NSString *)dataFilePath
{
return [[self documentsDirectory] stringByAppendingPathComponent:#"Checklists.plist"];
}
-(void)saveChecklistItems
{
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:_lists forKey:#"Checklists"];
[archiver finishEncoding];
[data writeToFile:[self dataFilePath] atomically:YES];
}
-(void)loadChecklists
{
NSString *path = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
NSData *data = [[NSData alloc] initWithContentsOfFile:path];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
_lists = [unarchiver decodeObjectForKey:#"Checklists"];
[unarchiver finishDecoding];
} else {
_lists = [[NSMutableArray alloc] initWithCapacity:20];
}
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
if ((self = [super initWithCoder:aDecoder])) {
_lists = [[NSMutableArray alloc] initWithCapacity:20];
Checklist *list;
list = [[Checklist alloc] init];
list.name = #"Birthdays";
[_lists addObject:list];
list = [[Checklist alloc] init];
list.name = #"Groceries";
[_lists addObject:list];
list = [[Checklist alloc] init];
list.name = #"Cool Apps";
[_lists addObject:list];
list = [[Checklist alloc] init];
list.name = #"To Do";
[_lists addObject:list];
for (Checklist *list in _lists) {
ChecklistItem *item = [[ChecklistItem alloc] init];
item.text = [NSString stringWithFormat:#"Item for %#", list.name];
[list.items addObject:item];
[self loadChecklists];
}
return self;
}
- (void)viewDidLoad // Use of undeclared identifier 'viewDidLoad'
{
[super viewDidLoad];
// 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)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [_lists count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
Checklist *checklist = _lists[indexPath.row];
cell.textLabel.text = checklist.name;
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
Checklist *checklist = _lists[indexPath.row];
[self performSegueWithIdentifier:#"ShowChecklist" sender:checklist];
}
#pragma mark - Table View Delegate Protocol
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
[_lists removeObjectAtIndex:indexPath.row];
NSArray *indexPaths = #[indexPath];
[tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
}
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"ShowChecklist"]) {
ChecklistViewController *controller = segue.destinationViewController;
controller.checklist = sender;
}
else if ([segue.identifier isEqualToString:#"AddChecklist"]) {
UINavigationController *navigationController = segue.destinationViewController;
ListDetailViewController *controller = (ListDetailViewController *)navigationController.topViewController;
controller.delegate = self;
controller.checklistToEdit = nil;
}
}
-(void)listDetailViewControllerDidCancel:(ListDetailViewController *)controller
{
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)listDetailViewController:(ListDetailViewController *)controller didFinishAddingChecklist:(Checklist *)checklist
{
NSInteger newRowIndex = [_lists count];
[_lists addObject:checklist];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:newRowIndex inSection:0];
NSArray *indexPaths = #[indexPath];
[self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)listDetailViewController:(ListDetailViewController *)controller didFinishEditingChecklist:(Checklist *)checklist
{
NSInteger index = [_lists indexOfObject:checklist];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
cell.textLabel.text = checklist.name;
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
UINavigationController *navigationController = [self.storyboard instantiateViewControllerWithIdentifier:#"ListNavigationController"];
ListDetailViewController *controller = (ListDetailViewController *)navigationController.topViewController;
controller.delegate = self;
Checklist *checklist = _lists[indexPath.row];
controller.checklistToEdit = checklist;
[self presentViewController:navigationController animated:YES completion:nil];
}
#end // Missing "end" | Expected "}"
AllListsViewController.h
#import <UIKit/UIKit.h>
#import "ListDetailViewController.h"
#interface AllListsViewController : UITableViewController <ListDetailViewControllerDelegate>
#end
ListDetailViewController.h
#import <UIKit/UIKit.h>
#class ListDetailViewController;
#class Checklist;
#protocol ListDetailViewControllerDelegate <NSObject>
-(void)listDetailViewControllerDidCancel:(ListDetailViewController *)controller;
-(void)listDetailViewController:(ListDetailViewController *)controller didFinishAddingChecklist:(Checklist *)checklist;
-(void)listDetailViewController:(ListDetailViewController *)controller didFinishEditingChecklist:(Checklist *)checklist;
#end
#interface ListDetailViewController : UITableViewController
#property (nonatomic, weak) IBOutlet UITextField *textField;
#property (nonatomic, weak) IBOutlet UIBarButtonItem *doneBarButton;
#property (nonatomic, weak) id <ListDetailViewControllerDelegate> delegate;
#property (nonatomic, strong) Checklist *checklistToEdit;
-(IBAction)cancel;
-(IBAction)done;
#end
Based on the fact that you are getting errors about a missing end and "expected '}', it sounds like you have mismatched curly brackets in your code. This sort of thing is really hard to spot by looking at code, but quite easy in Xcode. double-tap on each opening curly brace and Xcode will select the entire contents of the block up to the closing brace. Do that in your AllListsViewController.m file until you find the opening curly brace that does not have a corresponding closing brace.
This has been baffling me for a wile
I am successfully populating an array from a json call but the table view I want to poulate is not happening as the .
Can anyone see why?
I have tried a good few things but the array getting passed to the tableView is not getting populated with successfully retrieve json values
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
self.responseData = nil;
NSArray* categories = [(NSDictionary*)[responseString JSONValue] objectForKey:#"categories"];
[responseString release];
//fetch the data
for (NSDictionary* item in categories) {
NSString* c = [item objectForKey:#"CATEGORY_NAME"];
[self.tableViewArray addObject:[NSString stringWithFormat:#"%#", c]];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self loadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [tableViewArray 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.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// Configure the cell.
NSInteger rowNumber = indexPath.row;
NSString *stateName = [tableViewArray objectAtIndex:rowNumber];
cell.textLabel.text = stateName;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *message = [NSString stringWithFormat:#"You selected %#",[self.tableViewArray objectAtIndex:indexPath.row]];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Alert" message: message delegate:self cancelButtonTitle:#"Close" otherButtonTitles:nil];
[alert show];
[alert release];
}
EDIT
My .h is
#interface Medical_MeetingsViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {
NSMutableArray *tableViewArray;
NSMutableData *responseData;
IBOutlet UITableView *tableViewCat;
}
#property (nonatomic, retain) NSMutableArray *tableViewArray;
#property (retain, nonatomic) NSMutableData *responseData;
-(IBAction)loadData;
#end
is this correct?
Two things:
In the designer, do you have your TableView connected via an IBOutlet? This reference is necessary so that your code can send it instructions.
Second, I don't see you calling [tableview reloadData] anywhere, you'll need to call that after you finish gathering the data.
I'm a beginning programmer. And I had a question.
I currently have a Table View in my app. There are three rows to it, History, Theory, and Applied Use. I would like each one to go to a different detail view. However, each one only clicks to one of the detail views.
I think the issue is at
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
DetailViewController *dvController = [[DetailViewController alloc] initWithNibName:#"Magnets_AU_Aubrey" bundle:[
Please help any. The three XIB's are Magnets_AU_Aubrey, Magnets_History_Aubrey, and Magnets_Theory_Aubrey
#import "DisclosureButtonController.h"
#import "NavAppDelegate.h"
#import "DisclosureDetailController.h"
#import "DetailViewController.h"
#implementation DisclosureButtonController
#synthesize list;
- (void)viewDidLoad {
NSArray *array = [[NSArray alloc] initWithObjects:#"History", #"Theory", #"Applied Use", nil];
self.list = array;
[array release];
[super viewDidLoad];
}
- (void)viewDidUnload {
self.list = nil;
[childController release], childController = nil;
}
- (void)dealloc {
[list release];
[childController release];
[super dealloc];
}
#pragma mark -
#pragma mark Table Data Source Methods
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return [list count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString * DisclosureButtonCellIdentifier =
#"DisclosureButtonCellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
DisclosureButtonCellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:DisclosureButtonCellIdentifier] autorelease];
}
NSUInteger row = [indexPath row];
NSString *rowString = [list objectAtIndex:row];
cell.textLabel.text = rowString;
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
[rowString release];
return cell;
}
#pragma mark -
#pragma mark Table Delegate Methods
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
DetailViewController *dvController = [[DetailViewController alloc] initWithNibName:#"Magnets_AU_Aubrey" bundle:[
NSBundle mainBundle]];
[self.navigationController pushViewController:dvController animated:YES];
[dvController release];
dvController = nil;
}
- (void)tableView:(UITableView *)tableView
accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
if (childController == nil) {
childController = [[DisclosureDetailController alloc] initWithNibName:#"MagnetsAubreyCreditsDisclosureDetail" bundle:nil];
}
childController.title = #"Disclosure Button Pressed";
NSUInteger row = [indexPath row];
NSString *selectedMovie = [list objectAtIndex:row];
NSString *detailMessage = [[NSString alloc]
initWithFormat:#"School",selectedMovie];
childController.message = detailMessage;
childController.title = selectedMovie;
[detailMessage release];
[self.navigationController pushViewController:childController animated:YES];
}
#end
NSArray *array = [[NSArray alloc] initWithObjects:#"History", #"Theory", #"Applied Use", nil];
Now do the same for xibs. Create array and fill it with xib names. Then in didSelectRowAtIndexPath to get correct xib name apply the same logic as you do in cellForRowAtIndexPath for getting cell text.