0

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

4

2 回答 2

1

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

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

于 2013-08-19T19:08:38.207 回答
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.

于 2013-08-19T19:10:56.403 回答