標籤

2012年4月18日 星期三

NSNotificationCenter 例子

http://hi.baidu.com/%B0%AE%C9%FA%BB%EE%B0%AEqt/blog/item/8136f2d34838352a9b502799.html

1注册一个通知,当收到“ shake”的时候,触发eraseView这个函数
// Erase the view when recieving a notification named "shake" from the NSNotificationCenter object
// The "shake" nofification is posted by the PaintingWindow object when user shakes the device
[[NSNotificationCenter defaultCenteraddObserver:self                                                                  selector:@selector(eraseView)
                                             name:@"shake"
                                           object:nil];


2。eraseView函数实现
// Called when receiving the "shake" notification; plays the erase sound and redraws the view
-(void) eraseView
{
if(CFAbsoluteTimeGetCurrent() > lastTime + kMinEraseInterval) {
[erasingSound play];
[drawingView erase];
lastTime = CFAbsoluteTimeGetCurrent();
}
}
3。用户触发s事件,发送通知
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if (motion == UIEventSubtypeMotionShake )
{
            // User was shaking the device. Post a notification named "shake".
       [[NSNotificationCenter defaultCenter] postNotificationName:@"shake" 
                                            object:self];
}
}

沒有留言:

張貼留言