Я сделал простое приложение, чтобы решить проблему;это также первый раз, когда я использовал метод класса, поэтому извините, если я делаю это неправильно.
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
.
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)
отображается «(ноль)».