Problem with access to string from another class

2019-07-26 05:17发布

问题:

Hi i have two view controller: FirstViewController and SecondViewController

FirstViewController.h

#import <UIKit/UIKit.h>

@interface FirstViewController: {
 NSString *prStr;
  } 

 -(IBAction)setString;
 @property (nonatomic, retain) NSString *prStr;

 @end

 FirstViewController.m

 #import"FirstViewController.h"

 @implementation FirstViewController

 @synthesize prStr;

 -(IBAction)setString{
  prStr = [[NSString alloc]initWithFormat:@"1"];

   }

 SecondViewController.h

#import <UIKit/UIKit.h>

@class FirstViewController;

@interface SecondViewController: {
 FirstViewController *pr;
  } 

 -(IBAction)example;
 @property (nonatomic, retain) FirstViewController *pr;

 @end

 SecondViewController.m

 #import"SecondViewController.h"
 #import "FirstViewController.h"

 @implementation SecondViewController

 @synthesize pr;

 -(IBAction)example{
  NSLog(pr.prStr);
  if([pr.prStr isEqualToString:@"1"]==YES){

     //Do Something            }

   }

When i build and run app, at execution of IBAction example, on debugger console doesn't appear anything!! How can access to the string of FirstViewController from action of SecondViewController, in order to display it on the debugger console???

回答1:

First problem is that you haven't alloced it. Even if you alloc that, you should alloc as a singleton object.



回答2:

In your example, you never actually call setString, so the value is not actually set.

Except from that, i think it is just not good practive to use a propertie's getter directly as an IBAction (even though IBAction is equivalent to void)



回答3:

U allocate the memory for that object(pr) and try it out.