0

从 ViewController 类导入时 NSString 返回为 NULL

我想将字符串变量从一等导入到二等..但它没有导入

请在下面找到满足代码供您参考

ViewController:


@interface ViewController : UIViewController{

NSString * string;

@property(nonatomic, retain)NSString * string;

@end

@implementation ViewController
@synthesize string;

-(IBAction) login:(id) sender{
string = @"HI";
}

class2:

#import"ViewController.h"

@interface class2 : UIViewController{
ViewController * vc;
NSString * string1;

@property(nonatomic, retain)NSString * string1;

@end

@implementation ViewController
@synthesize string1;

-(IBAction) login:(id) sender{
NSLog(@"%@",vc.string);

@end
}

NSLog 在哪里返回 NULL!!!!

请帮助我!提前致谢

4

4 回答 4

0

@pradeepj 它返回Null是因为您的vc实例也是Null,我不确定您如何获得vc. 如果您使用的是 a ,那么您可以通过使用的属性UINavigationController来获取 的实例。vcviewControllersUINavigationController

于 2012-06-26T05:11:42.883 回答
0

第二个类不只是自动获取对您设置字符串值的同一个 class1 实例的引用。您的 class2 需要有一个可能从 class1 设置的属性,该属性引用您设置字符串的 class 1 的实例

//在第 1 类中

Class2 *vc = [[Class2 alloc] init];
vc.class1 = self;

[self.navigationcontroller pushViewController:vc animated:YES];
于 2012-06-26T05:12:18.797 回答
0

我不清楚您的代码,但如果您想将字符串从 class1 发送到 class2,那么您可以按照以下方法:

1.在 class2 中声明属性,与您声明的相同:

NSString * string1;
@property(nonatomic, retain)NSString * string1;

@synthesize string1;

2.然后在您导航到 class2 的 class1 中(从您初始化 class2 的位置)只需为您的 string1 分配所需的值,如下所示:

class2Obj.string1 = @"Hi";

在 class2 中,您可以访问 string1。

于 2012-06-26T05:14:12.750 回答
0

只是改变:

-(IBAction) login:(id) sender{
string = @"HI";
}

-(IBAction) login:(id) sender{
self.string = @"HI";
}

这将保留您的变量,以便您可以在其他地方找到它。只需确保vc在获取变量值之前已正确分配string变量。

于 2012-06-26T05:14:32.047 回答