从另一个类访问NSString将返回null。为什么?

时间:2011-11-20 03:30:03

标签: iphone objective-c nsstring

我已经制作了一个简单的应用来尝试解决问题;这也是我第一次使用类方法,如果我做错了,请原谅我。

ViewController.h

#import <UIKit/UIKit.h>
#import "ClassB.h"


@interface ViewController : UIViewController {
NSString *string;
}

@property (nonatomic,retain) NSString *string;

-(void)setString;
-(void)printStringViaClassB;

@end

ViewController.m

#import "ViewController.h"

@implementation ViewController
@synthesize string;

- (void)viewDidLoad
{
  NSLog(@"I'm inside viewDidLoad");
  [super viewDidLoad];
  [self setString];
  [self printStringViaClassB];
}

-(void)setString {
  NSLog(@"I'm inside the setString Method of the ViewController Class");
  string = @"HelloWorld";
  NSLog(@"String set to: %@",string);
}

-(void)printStringViaClassB {
  NSLog(@"I'm inside the printStringViaClassB method of the ViewController Class");
  [ClassB printLog];
}

ClassB.h

#import <Foundation/Foundation.h>
#import "ViewController.h"
@class ViewController;

@interface ClassB : NSObject{
}

+(void)printLog;

@end

ClassB.m

#import "ClassB.h"


@implementation ClassB {

}

+(void)printLog {
  NSLog(@"I'm in the PrintLog Method of ClassB");
  ViewController* VC = [[ViewController alloc] init];
  NSLog(@"The set string is: %@",VC.string);
}

@end

这是生成的日志;正如您所看到的,当从B而不是HelloWorld访问字符串时,它显示“(null)”。

    2011-11-20 14:21:18.223 ClassA[2253:f803] I'm inside viewDidLoad
    2011-11-20 14:21:18.224 ClassA[2253:f803] I'm inside the setString Method of the ViewController Class
    2011-11-20 14:21:18.225 ClassA[2253:f803] String set to: HelloWorld
    2011-11-20 14:21:18.225 ClassA[2253:f803] I'm inside the printStringViaClassB method of the ViewController Class
    2011-11-20 14:21:18.226 ClassA[2253:f803] I'm in the PrintLog Method of ClassB
    2011-11-20 14:21:18.226 ClassA[2253:f803] The set string is: (null)

1 个答案:

答案 0 :(得分:3)

运行以下代码时:ViewController* VC = [[ViewController alloc] init];,您正在创建ViewController的新实例。由于ViewController的新实例在加载之前没有它们的字符串值(即,直到运行viewdidload),因此您只是打印出null。

尝试将要从第二个类中访问的字符串值作为参数传递:

+(void)printLog:(NSString*)log;

+(void)printLog:(NSString*)log {
  NSLog(@"I'm in the PrintLog Method of ClassB");
  NSLog(@"The set string is: %@",log);
}

调用该函数,说[ClassB printLog:string];而不是[ClassB printLog];