2013-08-19 41 views
0

我有问题从nsobject类调用我的viewController。在这里我的代码:ios从不同的类回调viewController

的ViewController:

-(void)startTest:(NSString*)testToRun 
{ 
    ViewController *ViewController = [[[ViewController alloc] init] autorelease]; 
    SecondClass *secondClass = [[SecondClass alloc] init]; 
    secondClass.viewController = viewController; 
    [secondClass doSomething]; 
} 

-(void) createView 
{ 
    UIView *newView = [UIView alloc] initWithFrame:[self.view bounds]; 
    self.newView.backgroundColor = [UIColor whiteColor]; 
    [self.view addSubview:newView]; 
    [self.view bringSubviewToFront:newView] 
} 


NSObject classe: 

.h file 

#import "ViewController.h" 

@class ViewController; 

@interface SecondClass : NSObject 
{ 
    ViewController *viewController; 
} 

@property (nonatomic,retain) ViewController *viewController; 

-(void) doSomething; 


.m file 

-(void) doSomething 
{ 
    [viewController createView]; 

} 

任何人可能都知道我在做什么错误或我如何从我的NSObject类再打我的视图控制器?

+0

检查以确定viewController实际上仍然存在,并且在您调用它时不为零。 – Jeff

+0

您使用ARC吗? – Jeff

+0

在将视图控制器的指针传递给nsboject类的时刻不是nill,而是在nsobject类中的时候是nil,我不明白为什么 – HelenaM

回答

1

你指的是实例变量viewController但分配财产viewController

默认情况下,该属性自动合成为名为_viewController的实例变量。您可以将其更改为显式综合到您的实例变量,但更具规范性的是使用缺省_viewController并在您的实现文件中将其称为self.viewController

+0

这就是我的想法。除非你在处理getter/setting的地方有其他代码,否则这是HelenaM的问题。 – Jeff

0

我觉得你的问题出在下面的代码

-(void)startTest:(NSString*)testToRun 
{ 
    ViewController *ViewController = [[[ViewController alloc] init] autorelease]; 
    SecondClass *secondClass = [[SecondClass alloc] init]; 
    secondClass.viewController = viewController; 
    [secondClass doSomething]; 
} 

我相信上面这段代码在ViewController本身定义的,所以你应该做以下

-(void)startTest:(NSString*)testToRun 
{ 
    //ViewController *ViewController = [[[ViewController alloc] init] autorelease]; Don't do this, it is already initialized 
    SecondClass *secondClass = [[SecondClass alloc] init]; 
    secondClass.viewController = self;//assign self as reference 
    [secondClass doSomething]; 
} 

更多完美你也可以尝试使用Protocols

+0

如果我使用secondClass.viewController = self; secondClass中viewController的实例为nil。 – HelenaM

相关问题