我需要在我的应用程序的两个类(从 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 时,我可以在日志输出中读取“要传递的字符串:一个 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;
}
我可以在日志输出中读取“要传递的字符串:(null)”和 obv“接收的字符串:(null)”;难以置信,因为我可以完美地将全局变量 *stringToPass 传递给 Class_A 的每个方法,除了这个 -(NSString *) 方法。那么问题是什么?谢谢!