简体   繁体   English

从iphone视图传递到另一个的null值

[英]null value passed from a iphone view to another

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: 在视图AddBarView.m ,我有以下字符串:

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 现在在其他视图中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. NSLog返回一个(空)值。 Where is my fault? 我的错在哪里?

tx in advance! 提前发送!

You need to allocate memory to nameAdded string as follows and initialize it with nameField. 您需要按以下方式为nameAdded字符串分配内存,并使用nameField对其进行初始化。

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

edited Put the below line in the init method. 编辑将下面的行放在init方法中。

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

请参阅我的这篇文章,我在此处提供了有关如何将NSString从一个ViewController传递到另一个iOS教程 -将变量传递给视图控制器

nameAdded = nameField.text; nameAdded = nameField.text; you had only retain the value. 您只保留了价值。 If you edit the nameField.text later, nameAdded's value will be changed, too. 如果以后编辑nameField.text,nameAdded的值也将更改。 you should make a copy to keep the value. 您应该复制一份以保留其价值。 nameAdded = [nameField.text copy]; nameAdded = [nameField.text复制]; Check that in AddBarView's viewDidUnload function whether you has released nameAdded or not. 在AddBarView的viewDidUnload函数中检查是否已释放nameAdded。 Otherwise, the two nameAdded variables are same object? 否则,两个nameAdded变量是同一对象吗? please print their address. 请打印他们的地址。

Actually you are allocating and initializing the class that holds the textField. 实际上,您正在分配和初始化保存textField的类。 So it will always return you NULL value as the textField also allocated and initialized. 因此,由于textField也已分配和初始化,因此它将始终返回NULL值。 If the class 'AddBarView' called before the class that access it, you could simply pass it to the class. 如果在访问它的类之前调用​​了“ AddBarView”类,则可以将其传递给该类。 Instead 'AddBarView' called after the class that access it, you may want to store the textField value in a Global String!! 而是在访问它的类后调用“ AddBarView”,您可能希望将textField值存储在全局字符串中!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM