簡體   English   中英

了解前向聲明警告

[英]Understanding forward declaration warning

我正在用Objective-C編寫iPhone應用程序的第一行代碼。

這是代碼:

/* ViewController.h */
@protocol ImageFlowScrollViewDelegate;

@interface ViewController : UIViewController<ImageFlowScrollViewDelegate> {
    NSMutableArray *characters;
    UILabel *actorName;
}

/* ViewController.m */
#import "ImageFlowScrollView.h"
@implementation IMDBViewController
/* methods here */

/* ImageFlowScrollView.h */
@protocol ImageFlowScrollViewDelegate;

@interface ImageFlowScrollView : UIScrollView<UIScrollViewDelegate> {

    NSMutableArray *buttonsArray;
    id<ImageFlowScrollViewDelegate> imageFlowScrollViewDelegate;

}

@property(nonatomic, assign)id<ImageFlowScrollViewDelegate> imageFlowScrollViewDelegate;

- (id)initWithFrame:(CGRect)frame imageArray:(NSArray *) anArray;
- (void)focusImageAtIndex:(NSInteger) index;

@end


@protocol ImageFlowScrollViewDelegate<NSObject>

@optional
- (void)imageFlow:(ImageFlowScrollView *)sender didFocusObjectAtIndex: (NSInteger) index;
- (void)imageFlow:(ImageFlowScrollView *)sender didSelectObjectAtIndex: (NSInteger) index;
@end

這樣做,我得到一個

警告:找不到協議“ ImageFlowScrollViewDelegate”的定義

我可以使用以下方法修復它:

#import "ImageFlowScrollView.h"

@interface IMDBViewController : UIViewController<ImageFlowScrollViewDelegate> {
    NSMutableArray *characters;
    UILabel *actorName;
}

但是我想知道為什么前向聲明方法給我警告。

前向聲明定義符號,以便解析器可以接受它。 但是,當您嘗試使用協議(或類)時(如通過遵循協議進行的操作一樣),編譯器需要使用其定義來知道結果對象的布局和大小。

此外,僅在類或協議中使用該類或協議時(例如,在ivar中),您可以轉發該類或協議。 然后,編譯器僅需要知道符號的存在。 但是,在使用類(在實現文件中)時,需要在使用前聲明方法,因此需要包括聲明。

例如 :

/* AViewController.h */

@class AnotherClass;

@interface AViewController : UIViewController {
    AnotherClass* aClass; //only need the declaration of the name
}

@end

/* AViewController.m */

#import "AnotherClass.h"

@implementation AViewController

- (void) useAnotherClass {
     [AnotherClass aMessage]; //aMessage needs to be declared somewhere, hence the import
}

@end

此外,您已經知道必須提供實際的實現才能鏈接程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM