Problem with access to string from another class

孤人 提交于 2020-01-06 03:56:05

问题


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.



来源:https://stackoverflow.com/questions/4279310/problem-with-access-to-string-from-another-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!