【问题标题】:Passing variables in xcode returns null在 xcode 中传递变量返回 null
【发布时间】:2012-11-22 05:44:30
【问题描述】:

我检查了这里关于堆栈溢出的问题,我用同样的方式做,但仍然返回 NULL

在第一个视图中

在 firstviewcontroller.h 我有

@property (nonatomic, copy) NSString *Astring;

在firstviewcontroller.m中

#import "SecondViewController.h"
...
@synthesize Astring = _Astring;
...

- (IBAction)filterSearch:(id)sender {
NSlog(@"%@",Astring)

      }

在第二个viewcontroller.m中

#import firstviewcontroller.h
...
...
FirstViewController *controller = [[FirstViewController alloc]initWithNibName:@"FirstViewController" bundle:nil];
 controller.Astring = @"YES";

所以基本上我在 firstviewcontroller 中创建一个变量,然后在 secondviewcontroller 中将变量传递给第二个视图,但它总是返回 NULL...

是我的逻辑错了还是其他原因

【问题讨论】:

  • 您的#import 有问题,您似乎将它们倒置了。它不会纠正问题,但问题会更容易理解。
  • 在 NSLog 中尝试 self.Astring 而不是 Astring
  • @Yarlik 2bad 它仍然是 NULL
  • 除此之外,总是需要创建一个变量并将变量传递给它......你不能在另一个视图中看到它吗?
  • 您的代码令人困惑。您声明了一个名为“AString”的属性,然后将其合成,将“_Astring”分配为实例变量。在 SecondViewController 中,您将值 @"YES" 设置为属性,但在 NSLog() 中的 filterSearch 方法中,您使用不同的变量“Astring”,它不是属性或相应的实例变量。您是否在某处也有一个“Astring”变量,或者它只是一个错字?

标签: ios xcode variables


【解决方案1】:

这就是问题所在。您确实在更改 AString 的字符串值,但是在视图控制器的新实例上。这一行:FirstViewController *controller = [[FirstViewController alloc]initWithNibName:@"FirstViewController" bundle:nil]; 正在创建控制器的新实例。因此,现有控制器的视图控制器具有相同的属性。

那么你需要做的是找到一种方法来获取你的 firstViewController 的实例。

在 secondViewController.h 中,添加该属性。

#import "firstViewController.h"
 ...
@property (nonatomic, strong) firstViewController *firstController;

然后,在 secondViewController.m 中,您可以使用 firstController 调用字符串中的更改,它将包含您所追求的实例。我相信现在应该是这样的:

firstController.Astring = @"YES"

干杯!

【讨论】:

  • 没问题。但是我同意其他人的观点,总的来说,您的代码没有多大意义。我并不是要草率下任何结论,但您可能想要一本书来了解基础知识。 :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-08
  • 2021-05-14
相关资源
最近更新 更多