ios tableviews and json arrays - ios

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.

Related

retaining data outside of viewDidLoad in objective c ios

I am aware this question has been asked previously, but the answers provided have not solved my issue.
For instance, I have a very simple array of objects outlined in viewDidLoad:
#implementation MyViewController {
NSArray *tableData;
}
- (void)viewDidLoad
{
[super viewDidLoad];
tableData = [NSArray arrayWithObjects:#"Hello", #"My", #"Name", #"Is"];
NSLog(#"My Data: %#", tableData);
which is called in a tableView using cellForRowAtIndexPath
cell.nameLabel.text = [tableData objectAtIndex:indexPath.row];
This works fine and the NSLog shows my array. However, when i outline tableData outside of viewDidLoad, my array is (null).
My question is, how do I make my array available for the tableView when it is specified outside of ViewDidLoad?
edit: Here is my specific code:
#import <UIKit/UIKit.h>
#import "PhotoView.h"
#interface FrontViewController : UIViewController
#property (nonatomic, retain) UITableView *tableView;
#end
#import "FrontViewController.h"
#import "StreamScreen.h"
#import "API.h"
#import "PhotoView.h"
#import "StreamPhotoScreen.h"
#import "PrivateViewController.h"
#import "SWRevealViewController.h"
#import "PhotoScreen.h"
#import "RearViewController.h"
#import "SimpleTableCell.h"
#interface FrontViewController()
// Private Methods:
- (IBAction)pushExample:(id)sender;
#end
#implementation FrontViewController{
NSArray *tableData;
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = NSLocalizedString(#"Front View", nil);
SWRevealViewController *revealController = [self revealViewController];
[self.navigationController.navigationBar addGestureRecognizer:revealController.panGestureRecognizer];
UIBarButtonItem *revealButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:#"reveal-icon.png"]
style:UIBarButtonItemStyleBordered target:revealController action:#selector(revealToggle:)];
self.navigationItem.leftBarButtonItem = revealButtonItem;
// This works if I uncomment
//tableData = [NSArray arrayWithObjects:#"Hello", #"My", #"Name", #"Is", nil];
[self refreshStream];
}
-(void)refreshStream {
// call the "stream" command from the web API
[[API sharedInstance] commandWithParams:
[NSMutableDictionary dictionaryWithObjectsAndKeys:#"stream", #"command", nil]
onCompletion:^(NSDictionary *json) {
//got stream
[self showStream:[json objectForKey:#"result"]];
NSMutableArray *myData = [[NSMutableArray alloc] init];
myData = [json objectForKey:#"result"];
NSArray *userNameData = [myData valueForKey:#"username"];
[self loadData];
tableData = userNameData;
[self.tableView reloadData];
// I can see my json array in NSLog
NSLog(#"here's the results: %#", tableData);
}];
}
//This doesn't work either
//-(void)loadData {
// Add the data to your array.
//tableData = [NSArray arrayWithObjects:#"Hello", #"My", #"Name", #"Is", nil];
//NSLog(#"My Data: %#", tableData);
// Now load the table view.
// [self.tableView reloadData];
//}
-(void)showStream:(NSArray*)stream {
for (int i=0;i<[stream count];i++) {
NSDictionary* photo = [stream objectAtIndex:i];
}
NSArray *checkData = [stream valueForKey:#"username"];
//I can see my data in NSLog
NSLog(#"here's the results: %#", checkData);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [tableData count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 78;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableCell";
SimpleTableCell *cell = (SimpleTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"SimpleTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.nameLabel.text = [tableData objectAtIndex:indexPath.row];
cell.thumbnailImageView.image = [UIImage imageNamed:[thumbnails objectAtIndex:indexPath.row]];
cell.prepTimeLabel.text = [prepTime objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"didSelectRowAtIndexPath");
/*UIAlertView *messageAlert = [[UIAlertView alloc]
initWithTitle:#"Row Selected" message:#"You've selected a row" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];*/
UIAlertView *messageAlert = [[UIAlertView alloc]
initWithTitle:#"Row Selected" message:[tableData objectAtIndex:indexPath.row] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
// Display the Hello World Message
[messageAlert show];
// Checked the selected row
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"willSelectRowAtIndexPath");
if (indexPath.row == 0) {
return nil;
}
return indexPath;
}
#end
-(void)refreshStream {
// call the "stream" command from the web API
[[API sharedInstance] commandWithParams:
[NSMutableDictionary dictionaryWithObjectsAndKeys:#"stream", #"command", nil]
onCompletion:^(NSDictionary *json) {
//got stream
[self showStream:[json objectForKey:#"result"]];
NSMutableArray *myData = [json objectForKey:#"result"];
NSArray *userNameData = [myData valueForKey:#"username"];
}];
tableData = userNameData;
[self.tableView reloadData];
}
You're falling into a very common trap with asynchronous programming here.
commandWithParams takes a completion block, which is where you are getting the data out of the JSON. This block is not executed until the API call has returned. The sequence of events that happens when you run this code is:
commandWithParams is called
tableData is assigned to the contents of userNameData (which presumably you've also declared somewhere else otherwise this would not even compile)
reloadData is called
.... time passes
The completion block is executed and the JSON is read out into local variables, which are then instantly destroyed.
You need to move the two lines (points 2 and 3 in the list above) inside the completion block. There will be no data for your table until the block returns.
Ok my understanding of your question is that you want to assign variables to your NSArray in another method (not viewDidLoad) and then load the table view.
This is simple, just make a method which is in charge of adding the data to your array and then reload your table view like so:
-(void)viewDidLoad {
[super viewDidLoad];
// Call your method.
[self loadData];
}
-(void)loadData {
// Add the data to your array.
tableData = [NSArray arrayWithObjects:#"Hello", #"My", #"Name", #"Is"];
NSLog(#"My Data: %#", tableData);
// Now load the table view.
[myTableView reloadData];
}
Update 1
It would be much more helpful if you could share your code with us. How your and setting up your tableview, when its being called/etc....
Update 2
Ok well it seems obvious what yoru issue is. Your table view will never load like that. You need to call the tableview reloadData method outside the cellForRowAtIndexPath method.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *simpleTableIdentifier = #"SimpleTableCell";
SimpleTableCell *cell = (SimpleTableCell *)[self.tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"SimpleTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.nameLabel.text = [tableData objectAtIndex:indexPath.row];
cell.thumbnailImageView.image = [UIImage imageNamed:[thumbnails objectAtIndex:indexPath.row]];
cell.prepTimeLabel.text = [prepTime objectAtIndex:indexPath.row];
return cell;
}
So the method call [self.tableView reloadData]; should only be called in your refreshStream method.
Update 3
You need to initialize your NSMutableArray before you can add data to it. initialize it in your refreshStrem method like so:
-(void)refreshStream {
// call the "stream" command from the web API
[[API sharedInstance] commandWithParams:[NSMutableDictionary dictionaryWithObjectsAndKeys:#"stream", #"command", nil] onCompletion:^(NSDictionary *json) {
//got stream
[self showStream:[json objectForKey:#"result"]];
NSMutableArray *myData = [[NSMutableArray alloc] init];
myData = [json objectForKey:#"result"];
NSArray *userNameData = [myData valueForKey:#"username"];
}];
tableData = userNameData;
[self.tableView reloadData];
}
Update 4
Ok well after reading #jrturton answer, I think its safe to assume that my answer is rubbish. To anyone reading my answer, please view #jrturton post.
Well I feel pretty sheepish. The answer was simple. I was so hung up on Json and API that all I didn't check the basics. All I need was in my .h file:
#property (strong, nonatomic) IBOutlet UITableView *tableView;
I had originally had:
#property (nonatomic, retain) UITableView *tableView;

How to send value to anthor Page from table view iOS [duplicate]

This question already has answers here:
Passing data between view controllers
(45 answers)
Closed 8 years ago.
I have done for parsing data from JSON and put it show in Table view.
So I want to pass data (catID and catName )to another Page it's DetailPageController
how can I do like that? the below is my code.
Thanks in advance!
#import "ViewController.h"
#interface ViewController ()
{
NSMutableArray *myObject;
// A dictionary object
NSDictionary *dictionary;
// Define keys
NSString *catName;
NSString *catID;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
catName =#"Category Name";
catID=#"Category ID";
myObject = [[NSMutableArray alloc] init];
NSData *jsonSource = [NSData dataWithContentsOfURL:
[NSURL URLWithString:#"MY_URL"]];
id jsonObjects = [NSJSONSerialization JSONObjectWithData:
jsonSource options:NSJSONReadingMutableContainers error:nil];
for (NSDictionary *dataDict in jsonObjects) {
NSString *TheCatName = [dataDict objectForKey:#"cat_name"];
NSString *TheCatID = [dataDict objectForKey:#"cat_id"];
NSLog(#"cat_name: %#",TheCatName);
NSLog(#"cat_id: %#",TheCatID);
dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
TheCatName, catName,
TheCatID, catID,
nil];
[myObject addObject:dictionary];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return myObject.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Item";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell=[[UITableViewCell alloc]initWithStyle:
UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
NSDictionary *tmpDict = [myObject objectAtIndex:indexPath.row];
NSMutableString *textcat;
textcat = [NSMutableString stringWithFormat:#"%#",
[tmpDict objectForKeyedSubscript:catName]];
NSMutableString *catid;
catid = [NSMutableString stringWithFormat:#"ID: %# ",
[tmpDict objectForKey:catID]];
cell.textLabel.text = textcat;
cell.detailTextLabel.text= catid;
return cell;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
didSelectRowAtIndexPath
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *tmpDict = [myObject objectAtIndex:indexPath.row];
NSMutableString *catID;
catID = [NSMutableString stringWithFormat:#"%#",
[tmpDict objectForKeyedSubscript:cat_id]];
NSLog(#"didSelectRowAtIndexPath");
/*UIAlertView *messageAlert = [[UIAlertView alloc]
initWithTitle:#"Row Selected" message:#"You've selected a row" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];*/
UIAlertView *messageAlert = [[UIAlertView alloc]
initWithTitle:#"Row Selected" message:catID delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
// Display the Hello World Message
[messageAlert show];
// Checked the selected row
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
First import DetailPageController in TableviewController Class with help of following line.
#import "DetailPageController.h"
Now implement following method in your TableViewController Class
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
DetailPageController * detailPageControllerOBJ_ = [[ImageOptionViewController alloc]initWithNibName:#“XIBName bundle:nil];
detailPageControllerOBJ_.dicSelectedData = [self.arrayData objectAtIndex:indexPath.row];
[self.navigationController pushViewController:detailPageControllerOBJ_ animated:YES];
}
And in DetailPageController.h put following code.
#property (nonatomic,strong) NSDictionary * dicSelectedData;
You will get your selected data in dicSelectedData Dictionary

How show the data in UILabel from a NSMutableArray?

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.

How i use a NSMutableArray in two methods of my .m file?

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;
}

Add view from table view cell

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

Resources