它记录事件,然后发送通知告诉您它们发生了多少次。如果您想同时完成这两件事,请注意目前 0.0.X 版本会有破坏性更改……(但很可能容易处理)
提示:使用 Cocoapods
将 DHCCounter.{m,h} 拖到 Xcode 您最喜欢的 IDE 中。
//subscribe to the notification with the name "DHCEventCountChangeForEventName"+ your event name… this Example uses "MyEvent"
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gotMyEventNotification:) name:@"DHCEventCountChangeForEventNameMyEvent" object:nil];
////
//Bump the count
[DHCCounter bumpCountForEventName:@"MyEvent"];
//somewhere else //and we assume the count was previously 0
-(void)gotMyEventNotification:(NSNotification *)notification{
NSLog(@"count for MyEvent: %i",[notification.userInfo objectForKey:@"count"]); // logs 'count for MyEvent: 1'
}
当计数更改时,它会被广播到 NSNotificationCenter。因此,只需按照订阅 NSNotification 的过程进行操作即可。
您选择事件名称,通知名称会相应更改。
如果您将事件命名为 CheckBalance
,则发送到通知中心的名称将为 DHCEventCountChangeForEventNameCheckBalance
;在代码中,您可能像这样操作
NSString *const eventName = @"CheckBalance";
//subscribe
- (void)viewDidAppear:(BOOL)animated{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gotNotification:) name:[NSString stringWithFormat:@"DHCEventCountChangeForEventName%@",eventName] object:nil];
}
//unsubscribe!!
- (void)viewDidDisappear:(BOOL)animated{
[[NSNotificationCenter defaultCenter] removeObserver:notificationCatcher name:[NSString stringWithFormat:@"DHCEventCountChangeForEventName%@",eventName] object:nil];
}
NSInteger countForEvent=[DHCCounter countForEventName:@"someEventName"];
有一些设置计数的方式可以提高便利性
NSString *eventName=@"someEventName"
[DHCCounter bumpCountForEventName:eventName]; //increases count by one
[DHCCounter increaseCountForEventName:eventName byInteger:6]; //increase by a given NSInteger eg. 6
[DHCCounter setCount:22 ForEventName:eventName] // set count to a given NSInteger eg. 22
在订阅特定事件的 notification 并定义一个 seector(在我们的示例中为:gotNotification:
)之后,您将接收到作为输入参数的 NSNotification…这似乎是一个合适的地点来告诉您事件更改后的计数……所以我们就这样做了。
-(void)gotNotification:(NSNotification *)notification{
NSInteger count=notification.userInfo objectForKey:@"count";
if (count > 9000) {
//do your stuff once user has done a thing 9000 times
}
}
要点:事件的计数包含在 NSNotification 的 userInfo
字典中,其键为 @"count"