Model View Controller with UITextFieldDelegate issue - iphone

I'm working with something really easy, and I think I'm making a small mistake that I'm probably just not seeing here. I have this going on between my MVC to simply transfer a name from the AddViewController to the MasterViewController, and add it to the MasterController's UITableView. Although, I have "NSLogged" everything down to each step of the process, and what I'm basically getting out of it is that the text that's inputted into the "name" UITextField isn't passing itself into my NSString method, _aname.
Also, at one point, this was working and I was having trouble with setting the name to the MasterViewController from the AddViewController. So, if anyone could just give that part a look over too and make sure I have everything set up properly, I would hugely appreciate it.
In a nutshell, it looks like this.
MasterViewController.h
#property (nonatomic, strong) AddViewController *addViewController;
MasterViewController.m
- (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.text = [self.Name setName:name];
NSLog(#"%#", cell.textLabel.text);
return cell;
Name.h
- (NSString *)setName:(NSString *)name;
Name.m
- (NSString *)setName:(NSString *)name
{
[_nameStack addObject:name];
NSLog(#"Name set to: %#", name);
return name;
}
AddViewController.m
- (void)viewDidLoad
{
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(finalizeAdditionOfName:)];
NSUserDefaults *nameDefault = [NSUserDefaults standardUserDefaults];
nameInput.text = [nameDefault objectForKey:#"Name"];
}
- (IBAction)finalizeAdditionOfName:(id)sender
{
_name = [[Name alloc] init]
nameInput.text = _name;
[_name setName:_aname];
NSLog(#"Name set to (AddViewController): %#", _aname);
[self dismissViewControllerAnimated:YES completion:NULL];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([indexPath section] == 0) { // Section 1
if ([indexPath row] == 0) {
nameInput.delegate = self;
[nameInput setEnabled: YES];
[cell addSubview:nameInput];
[nameInput becomeFirstResponder]
nameInput.text = _aname;
NSUserDefaults *nameDefault = [NSUserDefaults standardUserDefaults];
[nameDefault setObject:_aname forKey:#"Name"];
}
}

if my comment doesn't turn out to be helpful, I made a sample project that I think shows how you might get the data from the text field to the table view. Tell me if you have any questions about it:
https://github.com/MaxGabriel/TextField-TableView-Example

Related

UITableView cell displays "null" value in index 0

I have textview in VC. Saving this textview using nsuserdefaults and get it later. In VC1 im getting saved textview and displaying in UITableView. But when i launch the app it automcatically displays "null" text in index 0.
VC:
-(void)save:(id)sender{
NSUserDefaults *userData1 = [NSUserDefaults standardUserDefaults];
[userData1 setObject:textView.text forKey:#"savetext"];
[userData1 synchronize];
}
VC1:
-(void) viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
// textArray=[[NSMutableArray alloc]init];
txt=[[UITextView alloc]initWithFrame:CGRectMake(0, 0, 320, 400)];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *savedValue = [prefs stringForKey:#"savetext"];
NSLog(#"saved is %#",savedValue);
txt.text = [NSString stringWithFormat:#"%#", savedValue];
NSLog(#"text.txt is %#", txt.text);
MyAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
if(![MyAppDelegate.textArray containsObject:txt.text]){
[MyAppDelegate.textArray addObject:txt.text];
}
NSUserDefaults *userData1 = [NSUserDefaults standardUserDefaults];
[userData1 setObject:MyAppDelegate.textArray forKey:#"save"];
[userData1 synchronize];
}
UITableView displays the text values using array:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSMutableArray* myMutableArrayAgain = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:#"save"]];
NSLog(#"array is %#",myMutableArrayAgain);
return [myMutableArrayAgain count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSMutableArray* myMutableArrayAgain = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:#"save"]];
NSLog(#"mycell is %#",myMutableArrayAgain);
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSLog(#"cell is %#",cell);
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
NSLog(#"cell inside is %#",cell);
}
// Configure the cell...
cell.textLabel.text = [myMutableArrayAgain objectAtIndex:indexPath.row];
[cell.textLabel setFont:[UIFont fontWithName:#"Arial-BoldMT" size:14]];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
This is all because the code is wrong at some places:
1) Nsmutable array with array is wrong:- as the userdefaults is returning you a single string.
So do it like this:-
NSUserDefaults *userData1 = [NSUserDefaults standardUserDefaults];
NSMutableArray* myMutableArrayAgain = [NSMutableArray arrayWithObject:[userData1 valueForKey:#"savetext"]];
2) In VC you are saving the value for key in "savetext" but in VC1 you are retrieving the value as "save", so change it, it has been done in the above code.
// The above 2 points would solve your problem but I would say don't code like this as it would consume more memory and would remove tidyness of your code. The code which you have done can be done in a very efficient way.
I tell you .
// Take first View controller VC and add IBAction to a button and a textView or textField what ever.
Write this code in VC :-
.h file
#interface demoViewController : UIViewController{
IBOutlet UITextField *txt1;
}
-(IBAction)getData:(id)sender;
.m file
// first include header file of the next controller where you want to redirect suppose XYZ
#import XYZ.h
-(IBAction)getData:(id)sender{
NSUserDefaults *userData1 = [NSUserDefaults standardUserDefaults];
[userData1 setObject:txt1.text forKey:#"savetext"];
demoViewController1 *demo=[[demoViewController1 alloc]initWithNibName:#"demoViewController1" bundle:nil];
[self.navigationController pushViewController:demo animated:NO];
}
// Take the second controller IN taht on ViewDisLoad or ViewDidAppear whatever you feel like
// Take a global MuttableArray
NSMutableArray *myMutableArrayAgain;
// I write this code on ViewDidload allocate the array here as MutableObject need to be allocated
NSUserDefaults *userData1 = [NSUserDefaults standardUserDefaults];
myMutableArrayAgain=[[NSMutableArray alloc]init];
[myMutableArrayAgain addObject: [userData1 valueForKey:#"savetext"]];
// Now table View Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [myMutableArrayAgain count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSLog(#"cell is %#",cell);
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
NSLog(#"cell inside is %#",cell);
}
// Configure the cell...
cell.textLabel.text = [myMutableArrayAgain objectAtIndex:indexPath.row];
[cell.textLabel setFont:[UIFont fontWithName:#"Arial-BoldMT" size:14]];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
// Apply this way you can do the stuff in less code and in a great way.

How to reload a uitable when the row of a different uitable's row is selected

I'm trying to reload a UITableView when the row of a different UITableView's row is selected. One of the problems I'm having is that both the UITableView's are in the same view. I would like a selection in Table1 to change the NSMutableArray that's used to populate Table2. And then reload the table.
At the moment it works fine, but only when the app re-lauches (or the view is popped off the stack and then re-visited) and viewWillAppear is called again
Here's my code:
- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:NO];
[self.navigationController setNavigationBarHidden:YES animated:NO];
self.navigationController.toolbarHidden = YES;
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
selectedTableString = [prefs stringForKey:#"selectedTableString"];
if ([selectedTableString isEqualToString:#"Italy"]) {
jsonStringCountry = #"http://****/v1/public/cities?country=it";
}
else if ([selectedTableString isEqualToString:#"Spain"]) {
jsonStringCountry = #"http://****/v1/public/cities?country=es";
}
else if ([selectedTableString isEqualToString:#"UK"]) {
jsonStringCountry = #"http://****/v1/public/cities?country=uk";
}
else if ([selectedTableString isEqualToString:#"Brazil"]) {
jsonStringCountry = #"http://****/v1/public/cities?country=br";
}
NSLog(#"from two t selectedTableString %#",selectedTableString);
// Download the yoodeal JSON
NSString *jsonString = [NSString stringWithContentsOfURL:[NSURL URLWithString:jsonStringCountry] encoding:NSStringEncodingConversionAllowLossy|NSUTF8StringEncoding error:nil];
NSLog(#"jsonStringCountry is %#", jsonStringCountry);
NSMutableArray *itemsTMP = [[NSMutableArray alloc] init];
// Create parser for the yoodeal api
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *results = [parser objectWithString:jsonString error:nil];
itemsTMP = [results objectForKey:#"results"];
self.displayItems = [itemsTMP copy];
}
My UITableView methods:
- (int)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [displayItems count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MainCell"];
if(cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"MainCell"];
}
// Get item from tableData
NSDictionary *item = (NSDictionary *)[displayItems objectAtIndex:indexPath.row];
cell.textLabel.text = [item objectForKey:#"name"];
[cell.textLabel setFont:[UIFont fontWithName: #"Asap-Bold" size: 14.0f]];
return cell;
}
You'll need to use the delegate method of UITablveView. The method is:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
This methods gets called when you click on the row of UITableView. Use this in following manner:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(tableView == Table1)
{
//do the changes in array you want to do.
[table2 reloadData];
}
else
{
//do the changes in array you want to do.
[table1 reloadData];
}
}
Create outlet for the table view
[self.yourTableView reloadData];
You should create a property of the UITableView called secondTableView and then use [secondTableView reloadData].
Use [tablename reloadData]; onclick.
When you are updating tableview contents, it will not refresh the view. You can only see changes once the view controller is reloaded.
For updating the table instantly you need to call the above code

Setting textLabel.text in UITableView using JSON data

I will preface the question with I am new to iOS and could use a little push. I have been trying to figure this out for a few days and fear I am not able to figure out the solution out of my frustration. It is my hope that some new eyes backed with experience will be able to help me out with this.
I have a JSON file that I want to use for various portions of my application. The file can be viewed at https://raw.github.com/irong8/stronger-nation-data/master/data.json for reference.
I am using Storyboards and want to accomplish this using the built in JSON support of iOS5. I created a new TableViewController subclass and have included the code below.
Here is my .h file
#import <UIKit/UIKit.h>
#interface StateTableViewController : UITableViewController
{
NSArray *StateList;
}
#property (nonatomic, retain) NSArray *StateList;
- (void) buildStateList;
#end
Here is my .m file
#import "StateTableViewController.h"
#implementation StateTableViewController
#synthesize StateList;
- (void)buildStateList {
NSString *jsonFile = [ [NSBundle mainBundle] pathForResource:#"data" ofType:#"json" ];
NSError *jsonError = nil;
NSData *jsonData = [NSData dataWithContentsOfFile:jsonFile options:kNilOptions error:&jsonError ];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&jsonError];
NSArray *jsonArray = [json objectForKey:#"states"];
self.StateList = jsonArray;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self buildStateList];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [StateList 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.text = [NSString stringWithFormat:#"%d", indexPath.row];
return cell;
}
I can loop through the StateList array using the following and see the state names I am looking for.
for (NSString *element in StateList) {
NSLog(#"element: %#", element);
}
When I load this view, a TableView is loaded with 50 rows (as expected as there are 50 state records in my data file) and each row is numbered 0-49. I am having trouble figuring out how to access the state name in my StateList array.
Any help along the way would be much appreciated!
You would populate your tableview's cells with data in cellForRow... Here is a slight modification of the default implementation in new projects:
- (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 = [StateList objectAtIndex:rowNumber];
cell.textLabel.text = stateName;
return cell;
}
EDIT The reason your app is now crashing is the object for the key "states" is a dictionary (as it should be according to the json at the link you posted) and you cannot simply cast it to an array. You can, however, ask the dictionary for an array of all of the keys. Which in this case will be the state names.
Change this line of code in buildStateList:
NSArray *jsonArray = [[json objectForKey:#"states"] allKeys];

How to copy pasteboard items into a table?

I have got an assignment here where I am supposed to
create an application, which copies the all the pasteboard items into
a table, that drills down into a detail view of said pasteboard item
.
Below, I give you my code of the RootViewController.m file. The program does not work and gives me an error of SIGABRT in this line cell.textLabel.text = cellValue;.
Could you tell me please, what could be possibly wrong here and thank you in advance.
#import "RootViewController.h"
#implementation RootViewController
#synthesize detailsViewController;
NSArray* pasteBoardItems;
- (void)viewDidLoad
{
// Get a reference to the system pasteboard
UIPasteboard* pasteBoard = [UIPasteboard generalPasteboard];
NSLog(#"%#", pasteBoard.items);
pasteBoardItems = [pasteBoard.items valueForKey:#"public.utf8-plain-text"];
pasteBoardItems = [pasteBoard.items valueForKey:#"public.item (kUTTypeItem)"];
self.navigationItem.title = #"Pasteboard";
[super viewDidLoad];
}
- (void)dealloc
{
[pasteBoardItems release];
[super dealloc];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [pasteBoardItems 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] autorelease];
}
NSString *cellValue = [pasteBoardItems objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
// Configure the cell.
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = [indexPath row];
NSString *rowValue = [pasteBoardItems objectAtIndex:row];
NSString *message = [[NSString alloc] initWithFormat:#"You have selected \"%#\"",rowValue];
if(self.detailsViewController == nil){
DetailsViewController *d = [[DetailsViewController alloc] initWithNibName:#"DetailsViewController" bundle:[NSBundle mainBundle]];
self.detailsViewController = d;
[d release];
}
[self.detailsViewController initWithTextSelected:message];
[self.navigationController pushViewController:self.detailsViewController animated:YES];
}
#end
SIGABRT in most cases means that you want to access released object.
In your case, I suggest to add line [pasteBoardItems retain]; at the end of - (void)viewDidLoad method.

Not able to access array with ids in another view controller in iphone

these is some code from my project..
for (index=0; index<[feed count]; index++) {
//NSLog(#"........%#",[feed objectAtIndex:2]);
NSString* forName=[feed objectAtIndex:index];
NSString *nameString = [forName valueForKey:#"name"];
NSLog(#"--------%#",nameString);
[nameArray addObject:nameString];
NSString *idString = [forName valueForKey:#"id"];
NSLog(#"--------%#",idString);
[idArray addObject:idString];
}
MyFriends *detailViewController = [[MyFriends alloc] initWithNibName:#"MyFriends" bundle:nil];
// ...
// Pass the selected object to the new view controller.
detailViewController.fbNames=nameArray;
detailViewController.fbIds=idArray;
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
My problem is in another controller when I am accessing array with names which is fbNames in another class it is showing me proper names,But when I am accessing fbIds which is the array with Ids ...they are showing me null..
how to correct this?
here...in this class ...fbNames are working fbIds are not..
- (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 [fbNames 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] autorelease];
}
// Configure the cell...
cell.textLabel.text=[fbNames objectAtIndex:indexPath.row];
NSLog(#"%#",cell.textLabel.text);
return cell;
}
NSString* forName=[feed objectAtIndex:index];
NSString *nameString = [forName valueForKey:#"name"];
I don't think NSString has valueForKey: