了解前向声明警告

时间:2010-08-27 14:52:16

标签: iphone forward-declaration

我正在使用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;
}

但我想知道为什么前瞻性声明方法会给我一个警告。

1 个答案:

答案 0 :(得分:1)

前向声明定义符号,以便解析器可以接受它。但是,当您尝试使用协议(或类)时 - 正如您通过遵循协议一样 - 编译器需要它的定义来了解结果对象的布局和大小。

此外,您可以在课堂上使用它时转发类或协议(例如,在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

此外,您已经知道必须提供实际的实施方式才能链接您的计划。