2013-07-15 48 views
1

有沒有辦法在.m文件中使用#import而不是.h文件?問題是我需要指定視圖控制器是.h文件中的ADBannerViewDelegate,如果在.m文件中導入iAd,它不會識別它。 有沒有辦法解決這個問題,或者我堅持不得已#importiAd每次我看到控制器我#import#導入iAd而不是.h

+0

始終包含頭文件(.h),而不是執行文件( .M)。將其導入到您使用的每個視圖控制器中。 – Raptor

+2

在.h中導入iAd – Kevin

回答

0

是的。您可以將所有iAd代碼放入.m文件中;你只需要使用類擴展(很常見)。類擴展,允許你聲明變量,包括委託,創建屬性等,全部來自.m文件。

類別擴展名位於.m文件的頂部,位於@implementation聲明之前。

例如:

//.h 
#import <UIKit/UIKit.h> 
@interface HomeViewController : UIViewController 
@end 


//.m 
#import "HomeViewController.h" 
#import <iAd/iAd.h> 

//The following is the class extension 
@interface HomeViewController() <ADBannerViewDelegate> //add any delegates here { 
    IBOutlet ADBannerView *ad; //A reference to the ad 
    BOOL someBOOL;    //You can put any variables here 
} 
- (void)someMethod:(id)sender; 
@property (nonatomic, strong) UIView *someView; 
@end 

注:類擴展必須以@end結束,然後將定期類主體如下:@implementation HomeViewController...

蘋果的文檔做好進一步的解釋類擴展。檢查出來here


同樣值得注意的是,這是一個自動創建的項目,稱爲「預編譯頭文件」。這個文件是一個地方,你可以導入你打算在整個項目中使用的其他類,所以你不必在每個類中手動導入它們。

繼承人PCH的例子:

#import <Availability.h> 

#ifndef __IPHONE_5_0 
#warning "This project uses features only available in iOS SDK 5.0 and later." 
#endif 

#ifdef __OBJC__ 
    #import <UIKit/UIKit.h> 
    #import <Foundation/Foundation.h> 
    #import <iAd/iAd.h> 
    //Put any other classes here and you can use them from any file 
#endif 

如果您在項目中的文件看,在支持文件,你應該看到You-Project-Name-Prefix.pch

+0

這似乎工作。謝謝! 是否有任何理由將協議放入.h文件中? – aeubanks

+0

很高興幫助。我不想說**從來沒有**任何理由將協議放在.h文件中,但是自從創建了類擴展後,我無法想到我擁有的實例。真正的類擴展,我發現最低限度需要.h文件 - 除了公共變量。 – Andrew

相關問題