1

我需要在我的应用程序的两个类(从 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 *) 方法。那么问题是什么?谢谢!

4

3 回答 3

1

- (void)viewDidLoad直到你调用之后才会被调用-(NSString *)stringPassage。尝试stringToPass = @"ANOTHER FANTASTIC STRING!";进入-(id)init方法Class_A

于 2012-10-02T16:06:28.507 回答
0

您正在调用init方法,而不是viewDidLoad方法。

如果将其添加到 Class_A,您将更接近:

-(id) init {
    self = [super init];
    if(self) {
        stringToPass = @"ANOTHER FANTASTIC STRING!";   
    }

    return self;
}
于 2012-10-02T16:27:46.487 回答
0

让我们有两个viewController,即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 
  }
于 2012-10-02T18:23:59.333 回答