er.*_*app 3 iphone notifications delegates protocols objective-c
协议或代表与NSNotifications之间有什么区别?什么是"观察者",它是如何运作的?
jtb*_*des 30
文档:协议
协议是定义对象响应的某些方法的接口.协议的关键是它们可以被任何类采用,保证对象响应这些方法.
如果您声明协议:
@protocol Photosynthesis
@required
- (void)makeFood:(id<Light>)lightSource;
@optional
+ (NSColor *)color; // usually green
@end
Run Code Online (Sandbox Code Playgroud)
然后你可以从其他不一定直接相关的类中采用它:
@interface Plant : Eukaryote <Photosynthesis>
// plant methods...
@end
@implementation Plant
// now we must implement -makeFood:, and we may implement +color
@end
Run Code Online (Sandbox Code Playgroud)
要么
@interface Cyanobacterium : Bacterium <Photosynthesis>
// cyanobacterium methods...
@end
@implementation Cyanobacterium
// now we must implement -makeFood:, and we may implement +color
@end
Run Code Online (Sandbox Code Playgroud)
现在,在其他地方,如果我们只关心协议的一致性,我们可以互换使用这些类中的任何一个:
id<Photosynthesis> thing = getPhotoautotroph(); // can return any object, as long as it conforms to the Photosynthesis protocol
[thing makeFood:[[Planet currentPlanet] sun]]; // this is now legal
Run Code Online (Sandbox Code Playgroud)
文档:Cocoa设计模式
这是在对象之间传递消息的两种方法.主要区别:
代表通常使用协议来实现:类通常会有类似的东西
@property (weak) id<MyCustomDelegate> delegate;
Run Code Online (Sandbox Code Playgroud)
它为代表提供了一组实现的方法.您可以使用
myObject.delegate = /* some object conforming to MyCustomDelegate */;
Run Code Online (Sandbox Code Playgroud)
然后该对象可以向其委托发送相关消息.有关常见示例,请参阅UITableViewDelegate协议.
另一方面,通知使用NSNotificationCenter实现.对象(或多个对象)只是将自身添加为特定通知的观察者,然后在由另一个对象发布时可以接收它们.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(notificationHappened:)
name:MyCustomNotificationName
object:nil];
Run Code Online (Sandbox Code Playgroud)
然后就实施吧
- (void)notificationHappened:(NSNotification *)notification {
// do work here
}
Run Code Online (Sandbox Code Playgroud)
您可以使用任何地方发布通知
[[NSNotificationCenter defaultCenter] postNotificationName:MyCustomNotificationName
object:self
userInfo:nil];
Run Code Online (Sandbox Code Playgroud)
并确保removeObserver:在完成后打电话!
| 归档时间: |
|
| 查看次数: |
17443 次 |
| 最近记录: |