2

When I pass a string to another view I have a null values. My code is:

In view AddBarView.m, where I have the string:

nameAdded = nameField.text;   //nameAdded is defined as NSString in AddBarView.h
NSLog(@"namefrom addbarview: %@", nameAdded);  OK it works here , NsLog return the textfild

Now in other view AddLocationController.m

@synthesize nameAdded;
- (void)addViewControllerDidFinish:(AddBarView *)controller
{
    AddBarView *controllerAdd;
    NSLog(@"namefrom addbarview: %@", controller.nameAdded);  //here

    [self dismissModalViewControllerAnimated:YES];
}

the NSLog return a (null) value. Where is my fault?

tx in advance!

Yogesh Prajapati
  • 4,770
  • 2
  • 36
  • 77
doxsi
  • 1,002
  • 19
  • 42

4 Answers4

2

You need to allocate memory to nameAdded string as follows and initialize it with nameField.

nameAdded=[[NSString alloc] initWithFormat:@"%@",nameField.text];

edited Put the below line in the init method.

nameAdded=[NSString stringWithFormat:@"%@",nameField.text];
Sanchit Paurush
  • 6,114
  • 17
  • 68
  • 107
  • nameAdded is defined in the .h file as NSString and resctive property and syntesize. The NSLog(@"%@", nameAdded); return the correct value, but null in the other view – doxsi Jul 13 '12 at 12:31
  • @doxsi It is because when you call it from another view the textfield does not get its value. – Sanchit Paurush Jul 13 '12 at 12:35
2

See my this post I gave a Tutorial here for how to pass a NSString from one ViewController class to another iOS - Passing variable to view controller

Community
  • 1
  • 1
TheTiger
  • 13,264
  • 3
  • 57
  • 82
2

nameAdded = nameField.text; you had only retain the value. If you edit the nameField.text later, nameAdded's value will be changed, too. you should make a copy to keep the value. nameAdded = [nameField.text copy]; Check that in AddBarView's viewDidUnload function whether you has released nameAdded or not. Otherwise, the two nameAdded variables are same object? please print their address.

Huangzy
  • 149
  • 1
  • 6
1

Actually you are allocating and initializing the class that holds the textField. So it will always return you NULL value as the textField also allocated and initialized. If the class 'AddBarView' called before the class that access it, you could simply pass it to the class. Instead 'AddBarView' called after the class that access it, you may want to store the textField value in a Global String!!

Nina
  • 1,579
  • 2
  • 21
  • 51
  • Tx. how Could I define a Global string? – doxsi Jul 15 '12 at 10:36
  • You can do that in many ways!! Usually, I'll create a C-file (holds .h file alone). Declare your string there. Import that in '.pch'. Now you can access it in your class :-) – Nina Jul 16 '12 at 06:01