ios从不同的类调用viewController

时间:2013-08-19 18:42:33

标签: iphone ios xcode ipad viewcontroller

我在从nsobject类调用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类中回调我的视图控制器?

2 个答案:

答案 0 :(得分:1)

您指的是实例变量 viewController,但正在分配属性 viewController

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

答案 1 :(得分: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