一个.h文件,带有两个@interface并在.m文件中调用

时间:2014-07-21 09:35:45

标签: ios objective-c uiview uiviewcontroller

.h文件中,我有2个这样的接口:

@interface Main : UIViewController
@property (strong, nonatomic) IBOutlet UIView *MainView;
@end


@interface Sub : UIViewController
@property (strong, nonatomic) IBOutlet UIView *testView;
@end

之后,在.m文件中,我有这样的实现。如何在testView实现中调用Main(在不同的接口中声明)?

@implementation Main

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
@end

编辑 - 我不能拥有或者我不想拥有单独的.h和.m文件,因为我有很多这样的界面。我担心我需要创建很多.h和.m文件。所以,我将所有这些组合在1 .h和1 .m文件中。

enter image description here

3 个答案:

答案 0 :(得分:0)

你做不到。因为testView封装在另一个类中,而该类未在Main类中实例化。您只在一个.h和.m文件中有两个不同的类。您可以创建子类的实例,但也许您应该重新考虑您的类设计。

顺便问一下,你为什么这样做?为什么不拆分两个.h / .m文件?

答案 1 :(得分:0)

你需要实现Sub Class也是同一个文件(.m文件)

@implementation Sub

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
@end

然后在主init方法中

@implementation Main

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

         Sub * s1 = [Sub new];
           // Now you can use s1.testView... and so on
    }
    return self;
}
@end

答案 2 :(得分:-2)

在Main实现中定义Sub变量,您可以使用变量的testView。

但首先,写一下

@class Sub; 

@interface Main : UIViewController

相关问题