Iphone 如何从其他类引用MainViewController?

Iphone 如何从其他类引用MainViewController?,iphone,reference,Iphone,Reference,我正在构建一个iPhone实用程序应用程序,它使用UIImageView显示动画。在MainViewController的viewDidLoad()方法中,我正在创建CustomClass的实例,然后设置动画: - (void)viewDidLoad { [super viewDidLoad]; cc = [CustomClass new]; NSArray * imageArray = [[NSArray alloc] initWithObjects: [UII

我正在构建一个iPhone实用程序应用程序,它使用UIImageView显示动画。在MainViewController的viewDidLoad()方法中,我正在创建CustomClass的实例,然后设置动画:

- (void)viewDidLoad { [super viewDidLoad]; cc = [CustomClass new]; NSArray * imageArray = [[NSArray alloc] initWithObjects: [UIImage imageNamed:@"image-1-off.jpg"], [UIImage imageNamed:@"image-2-off.jpg"], [UIImage imageNamed:@"image-3-off.jpg"], [UIImage imageNamed:@"image-4-off.jpg"], nil]; offSequence = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; offSequence.animationImages = imageArray; offSequence.animationDuration = .8; offSequence.contentMode = UIViewContentModeBottomLeft; [self.view addSubview:offSequence]; [offSequence startAnimating]; } -(无效)viewDidLoad { [超级视图下载]; cc=[CustomClass new]; NSArray*imageArray=[[NSArray alloc]initWithObjects: [UIImage ImageName:@“image-1-off.jpg”], [UIImage ImageName:@“image-2-off.jpg”], [UIImage ImageName:@“image-3-off.jpg”], [UIImage ImageName:@“image-4-off.jpg”], 零]; offSequence=[[UIImageView alloc]initWithFrame:CGRectMake(0,0320480)]; offSequence.animationImages=imageArray; offSequence.animationDuration=.8; offSequence.contentMode=UIViewContentModeBottomLeft; [self.view addSubview:offSequence]; [非顺序启动]; } 那很好。但是,我希望能够将上面设置UIImageView的所有代码移动到我的CustomClass中。问题在倒数第二行:

[self.view addSubview:offSequence]

我基本上需要将“self”替换为对MainControllerView的引用,这样我就可以从CustomClass中调用addSubview。我尝试创建一个名为mvc的CustomClass实例变量和一个setter方法,该方法将对MainViewController的引用作为参数:

- (void) setMainViewController: (MainViewController *) the_mvc { mvc = the_mvc; } -(void)setMainViewController:(MainViewController*)将 { mvc=_mvc; } 然后我在MainViewController中这样调用它:

[cc setMainController:MainViewController:self]


但这会产生各种各样的错误,我可以在这里发布,但我觉得我可能把它复杂化了。有没有更简单的方法来引用实例化我的CustomClass的MainViewController?

最干净的方法是创建UIImageView的子类并创建接受数组的自定义初始值设定项。所以

@interface MyCustomImageView:UIImageView {
//...
}

-(id) initWithFrame(CGRect) aRect animationImages:(NSArray *) imageArray;
@end

然后在主视图控制器中初始化自定义图像视图,填充它并将其添加到子视图中。这将使一切都很好地封装、模块化和可重用

谢谢,那太迷人了。。。我没有想过将UIImageView子类化,但将事物保留在它们的位置是非常有意义的。实际上,我用以前的方法找到了另一个可行的解决方案:我试图传入和存储对MainViewController的引用的方式出现了问题,主要是围绕着我将其类型称为MainViewController这一事实——我将其切换到了NSObject,它工作起来很有魅力。