2011-04-27 50 views
1

我正在查看Apple的示例代码lazy table image loading。我看到他们有两条以@protocol ParseOperationDelegate开头的行。他们为什么要这样做两次?我所看过的Objective C协议的所有文档都不会告诉你两次。为什么在Apple的示例代码中定义了两次协议?

@class AppRecord; 

@protocol ParseOperationDelegate; 

//@interface ParseOperation : NSOperation <NSXMLParserDelegate> 
@interface ParseOperation : NSOperation 
{ 
@private 
    id <ParseOperationDelegate> delegate; 

    NSData   *dataToParse; 

    NSMutableArray *workingArray; 
    //AppRecord  *workingEntry; 
    //NSMutableString *workingPropertyString; 
    //NSArray   *elementsToParse; 
    //BOOL   storingCharacterData; 
} 

- (id)initWithData:(NSData *)data delegate:(id <ParseOperationDelegate>)theDelegate; 

@end 

@protocol ParseOperationDelegate 
- (void)didFinishParsing:(NSArray *)appList; 
- (void)parseErrorOccurred:(NSError *)error; 
@end 

回答

6

@protocol ParseOperationDelegate;行没有定义协议。这是一个前向声明。基本上它是说“存在一个名为ParseOperationDelegate的协议,并在代码中的其他位置定义”。

他们这样做,以便编译器不会死在id <ParseOperationDelegate> delegate;线上的错误。另一种方法是将整个协议定义放在接口定义之前(我个人认为这将是更好的解决方案)。

在这样一个简单的例子中,我认为在进行前向声明方面没什么意义。但是你可以很容易地想象一个更复杂的情况,其中协议定义可能存在于它自己的头文件中(或者在某个其他类的头文件中)。在这种情况下,使用前向声明可以避免将协议的头文件放入类的头文件中。这是一个很小的差异,但它确实很有用。

相关问题