获得无法识别的选择器'来自NSNotificationCenter

时间:2016-08-22 11:01:08

标签: objective-c observer-pattern nsnotificationcenter couchbase-lite

我试图在NSNotificationCenter中实现观察者。我没有使用self作为观察者,而是想创建一个小对象来实现它:

typedef void (^ErrorCallback)(NSError*);
typedef void (^SuccessCallback)();
typedef void (^ReplicationChanged) (NSNotification*);

@interface SyncParams : NSObject

@property (copy) ErrorCallback errorCallback;
@property (copy) SuccessCallback successCallback;
@property (copy) ReplicationChanged replicationChanged;//this used to observe

- (void)replicationChanged:(NSNotification*)notification;

@end

@implementation SyncParams

@end

然后我创建了一个观察者的实例:

SyncParams* params = [SyncParams alloc];
params.replicationChanged = ^(NSNotification* notification) {
    //do stuff here
}; 

最后将其添加到NSNotificationCenter:

[[NSNotificationCenter defaultCenter] addObserver: params
                                         selector: @selector(replicationChanged:)
                                             name: kCBLReplicationChangeNotification
                                           object: replicationObject];

但是我收到了这个错误:Exception '-[SyncParams replicationChanged:]: unrecognized selector sent to instance 0x7ff945c049a0' was thrown

我对objective-c很新!有什么指针吗?

1 个答案:

答案 0 :(得分:0)

是和否,我最终得到了以下内容:

[[NSNotificationCenter defaultCenter] addObserverForName:kCBLReplicationChangeNotification object:repl queue:nil usingBlock:^(NSNotification *notification) {

    NSString *status;
    if (repl.status == kCBLReplicationActive) {
        NSLog(@"Repication in progress");
        status = @"in-progrss";
    } else if (repl.status == kCBLReplicationOffline) {
        NSLog(@"Sync in offline");
        status = @"offline";
    } else if (repl.status == kCBLReplicationStopped) {
        NSLog(@"Sync in stopped");
        status = @"stopped";
    } else if (repl.status == kCBLReplicationIdle) {
        NSLog(@"Sync in idle");
        status = @"idle";
    }

    NSError *error = repl.lastError;
    if(error) {
        status = @"error";
        NSLog(@"replication error %@", error.code);
    }

    NSDictionary *dictionary = @{
                                 @"type": type,
                                 @"changesCount": @(repl.changesCount),
                                 @"completedChangesCount": @(repl.completedChangesCount),
                                 @"running": @(repl.running),
                                 @"status": status,
                                 @"suspended": @(repl.suspended),
                                 };

    [self sendEventWithName:@"replicationChanged" body:dictionary];

}];

我开始时只会收到一个回调。