我需要在我的应用程序的两个类(从ViewController Class_A到ViewController Class_B)之间传递NSString,我已经在StackOverflow上搜索了,但这是我的情况的简化代码:
Class_A.h
#import "Class_B.h"
@interface ViewController : UIViewController {
NSString *stringToPass;
}
@property (retain, nonatomic) NSString *stringToPass;
-(NSString *)stringPassage:(id)sender;
@end
Class_A.m
- (NSString *)stringPassage:(id)sender{
NSString *string = @"A FANTASTIC STRING!"; //here I define string INTO the - (NSString *) method
NSLog(@"String to pass: %@",string);
return string;
}
Class_B.h
#import "Class_A.h"
Class_B.m
- (void)viewDidLoad
{
[super viewDidLoad];
Class_A *Class_A_Instance = [[Class_A alloc] init];
NSString *importedString = [Class_A_Instance stringPassage:self];
[Class_A_Instance release];
NSLog(@"Received String: %@",importedString);
// Do any additional setup after loading the view from its nib.
}
嗯,它就像一个魅力!当加载Class_B时,我可以在日志输出中读取“String to pass:A FANTASTIC STRING!”和“收到的字符串:一个神奇的字符串!”;但如果我只改变这部分代码(我需要它!):
Class_A.m
- (void)viewDidLoad
{
[super viewDidLoad];
stringToPass = @"ANOTHER FANTASTIC STRING!";
// Do any additional setup after loading the view, typically from a nib.
}
- (NSString *)stringPassage:(id)sender{
NSString *string = stringToPass; // here I must call the string FROM another method of Class_A (in this example from - (void)viewDidLoad
NSLog(@"String to pass: %@",string);
return string;
}
我可以在日志输出中读取“String to pass:(null)”和obv“Received String:(null)”;它令人难以置信,因为我可以将全局变量* stringToPass完美地传递给Class_A的每个方法,除了这个 - (NSString *)方法。那么问题是什么?谢谢!
答案 0 :(得分:1)
- (void)viewDidLoad
之后才会调用{p> -(NSString *)stringPassage
。尝试将stringToPass = @"ANOTHER FANTASTIC STRING!";
移至-(id)init
的Class_A
方法
答案 1 :(得分:0)
您正在调用init
方法,而不是viewDidLoad
方法。
如果你将它添加到Class_A,你会更接近:
-(id) init {
self = [super init];
if(self) {
stringToPass = @"ANOTHER FANTASTIC STRING!";
}
return self;
}
答案 2 :(得分:0)
我们有两个viewControllers,即FirstVC和SecondVC。 在SecondVC中创建一个字符串,
@interface SecondVC : UIViewController { NSString *string2pass; }
@property (retain, nonatomic) NSString *string2pass;
在FirstVC中,当您要呈现SecondVC时,将字符串传递为
- (void)presentSecondView
{
SecondVC *secondVC = [[SecondVC alloc]initWithNibName:@"SecondVC" bundle:nil];
secondVC.string2pass = @"this is a passing string";
[self presentModalViewController:resView animated:YES];
}
- (void)viewDidLoad
{
NSString *string4mFirstVC = string2Pass
}