Iphone 从另一个类访问字符串时出现问题
嗨,我有两个视图控制器:FirstViewController和SecondViewControllerIphone 从另一个类访问字符串时出现问题,iphone,objective-c,class,nsstring,Iphone,Objective C,Class,Nsstring,嗨,我有两个视图控制器:FirstViewController和SecondViewController FirstViewController.h #import <UIKit/UIKit.h> @interface FirstViewController: { NSString *prStr; } -(IBAction)setString; @property (nonatomic, retain) NSString *prStr; @end 当我构建并
FirstViewController.h
#import <UIKit/UIKit.h>
@interface FirstViewController: {
NSString *prStr;
}
-(IBAction)setString;
@property (nonatomic, retain) NSString *prStr;
@end
当我构建并运行应用程序时,在执行IBAction示例时,调试器控制台上并没有显示任何内容!!如何从SecondViewController的操作访问FirstViewController的字符串,以便在调试器控制台上显示该字符串?在您的示例中,您从未实际调用setString,因此没有实际设置该值
除此之外,我认为直接将属性的getter用作iAction(即使iAction相当于void)是不好的做法。U为该对象分配内存(pr)并尝试一下。第一个问题是您没有分配它。
即使您分配了它,也应该将其作为单例对象进行分配。问题已解决,我在appdelegate中声明了一个NSString,并将其用作全局变量:我在第一个视图控制器中设置该字符串,并在第二个视图控制器中使用appdelegate.prStr读取该字符串
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 }
}