2014-07-21 33 views
-3

.h文件,我有2個接口,這樣的:與.m文件的兩個@interface並調用一個.h文件中

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


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

之後,在.m文件,我已經實現這樣的。如何在Main實現中調用testView(在不同的接口中聲明)?

@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

+2

創建子實例(子* ASUB = .. ),然後你可以訪問testView,如:aSub.testView。但是這些更改僅適用於「主要」實例。 –

+0

謝謝。我會這樣做。 –

+0

誰投這個問題?我可以知道爲什麼嗎?我從來沒有給過任何理由的投票人 –

回答

0

你不能。因爲testView被封裝在另一個類中,該類不在Main類中實例化。在一個.h和.m文件中分別只有兩個不同的類。你可以創建一個你的子類的實例,但也許你應該重新考慮你的類設計。

順便說一句,你爲什麼這樣做?爲什麼不分成兩個.h/.m文件?

+0

嗨..我編輯了問題。我不能或者我不想分開.h和.m文件,因爲我有很多接口,如圖所示。 –

-2

在Main實現中定義一個Sub變量,您可以使用變量的testView。

但首先,寫

@class Sub; 

@interface Main : UIViewController 

之前。

+1

或者他們可以創建一個正常的實例。當他們將'.h'文件的'import'導入'.m'文件時,它將包含'Sub'的接口,因此他們需要做的就是'Sub * sub = [[Sub alloc] init]; '做'@class sub'是沒有意義的-1 – Popeye

0

需要實現子類也是同樣的文件(.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 
相關問題