在实现文件中重复声明类接口有什么意义?

3
在一些苹果iPhone的示例中,有些属性在头文件中声明,而有些在实现文件中声明。例如,在Seismic XML示例中:
ParseOperation.h
@interface ParseOperation : NSOperation {
NSData *earthquakeData;

@private
NSDateFormatter *dateFormatter;

// these variables are used during parsing
Earthquake *currentEarthquakeObject;
Contact *currentContactObject;
NSMutableArray *currentParseBatch;
NSMutableString *currentParsedCharacterData;

BOOL accumulatingParsedCharacterData;
BOOL didAbortParsing;
NSUInteger parsedEarthquakesCounter;
}

@property (copy, readonly) NSData *earthquakeData;

@end

ParseOperation.m

@interface ParseOperation () <NSXMLParserDelegate>
  @property (nonatomic, retain) Earthquake *currentEarthquakeObject;
  @property (nonatomic, retain) NSMutableArray *currentParseBatch;
  @property (nonatomic, retain) NSMutableString *currentParsedCharacterData;
  @property (nonatomic, retain) Contact *currentContactObject;
@end

在实现文件中,额外接口声明的作用是什么?
1个回答

5

这只是公共类和私有类接口之间的区别。头文件描述了公共接口,但是一些属性仅供类本身使用而非协作者使用。这些私有属性通常以你所描述的方式在实现文件中声明为分类或类扩展。

// Foo.h – the public interface
@interface Foo : NSObject {…}

// Collaborators can only read bar.
@property(readonly) int bar;
@property(readonly) int baz;

@end

// Foo.m
#import "Foo.h"

// Private interface
@interface Foo ()

// Inside class implementation we can also change bar.
@property(assign) int bar;
@property(assign) int other;

@end

@implementation Foo
@synthesize bar, baz, other;
…
@end

为什么不使用传统的私有、公共访问修饰符呢? - Abhinav Gujjar
你不希望将变量声明为public,因为这会破坏封装性。有时即使在类的实现中,你也不想直接访问变量,因为这会涉及到内存管理或者你希望访问器做一些额外的工作,比如发送 KVO 通知或更新其他值。 - zoul
嗯...理论上,如果“属性”也有访问修饰符,那么在实现文件中声明它们的需要就会被消除。对吧? - Abhinav Gujjar
如果访问修饰符允许您在类实现中创建一个可读写的属性,并对其他人只读,那就没问题了。 - zoul
在实现foo类中,添加另一个类似接口的类foo1: NSObject {NSMutableArray *observers; CADisplayLink *displayLink;} - (void)removeObserver:(id)object; 实现foo1 - (void)removeObserver:(id)object {nslog(@"%@",object);} 如何访问foo1类的removeObserver方法? - SnakingPrabhu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接