msec
msec

Reputation: 252

Accessing NSString from another class returns null. Why?

I have made a simple app to try a nut out the problem; this is also the first time I have used a class method so excuse me if I am doing it wrong.

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

This is the resulting log; as you can see, it is showing "(null)" when accessing the string from B instead of HelloWorld.

    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)

Upvotes: 0

Views: 1164

Answers (1)

aleph_null
aleph_null

Reputation: 5786

When you run the following code: ViewController* VC = [[ViewController alloc] init];, you are creating a NEW instance of ViewController. Since new instances of ViewController don't have their string value until their loaded (i.e., until viewdidload is run), you are simply printing out null.

Try passing in the string value you want to access from the second class as a parameter:

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

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

to call the function, say [ClassB printLog:string]; instead of [ClassB printLog];

Upvotes: 3

Related Questions