0

我正在为 iPhone 应用程序编写 Objective-c 中的第一行。

这是代码:

/* 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;
}

但我想知道为什么前向声明方法给了我一个警告。

4

1 回答 1

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

此外,您已经知道必须提供实际实现才能链接您的程序。

于 2010-08-27T14:58:18.870 回答