NSOperationQueue ....发送了无法识别的选择器

NSOperationQueue ....unrecognized selector sent

我正在尝试实现一个联系人应用程序。

在 MyContactsViewController 中,我正在尝试访问联系人,如果访问被授予,我将从我的地址簿中获取联系人。 ContactHandler 是我的模型 class(单例),它具有名为 getAllContacts 的方法来获取 NSMutableArray 中的联系人。

- (void)viewDidLoad {
    [super viewDidLoad];
    contactHandler = [ContactHandler sharedInstance];
    if(!self.accessGranted){
        NSOperationQueue *queue =[[ NSOperationQueue alloc]init];
        [queue performSelectorOnMainThread:@selector(getAccessToAddressBook) withObject:self waitUntilDone:YES];
        contactList = [contactHandler getAllContacts];
    }
    else{
        contactList = [contactHandler getAllContacts];
    }

}

-(BOOL)getAccessToAddressBook{

    CNContactStore * contactStore = [[CNContactStore alloc] init];

    if( [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusNotDetermined){

        [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if(granted){
                self.accessGranted = YES;
            }
            else{
                self.accessGranted = NO;
            }
        }];
    }
    else if( [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts]== CNAuthorizationStatusAuthorized){
        self.accessGranted = YES;
    }
    else{
        self.accessGranted = NO;
    }
    return self.accessGranted;
}

但是我收到这个错误 -

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSOperationQueue getAccessToAddressBook]: unrecognized selector sent to instance 0x137630700'

谁能帮忙。

在这一行中:performSelectorOnMainThread 你正在传递 withObject:self,而在方法定义中,即 (BOOL)getAccessToAddressBook你没有使用它,这导致了崩溃,所以使 withObject:nil ,如果您不想将任何对象或值传递给该方法。

更改此行:-

 [queue performSelectorOnMainThread:@selector(getAccessToAddressBook) withObject:self waitUntilDone:YES];

对此:-

 [queue performSelectorOnMainThread:@selector(getAccessToAddressBook) withObject:nil waitUntilDone:YES];

或者更好的方法是这样写:-

   NSOperationQueue *opQueue=[NSOperationQueue new];
    NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(getAccessToAddressBook) object:nil];
 [opQueue addOperation:op ];

你的问题是这一行:

[queue performSelectorOnMainThread:@selector(getAccessToAddressBook) withObject:self waitUntilDone:YES];

您要求 queue 执行 getAccessToAddressBookself 谁拥有此选择器

如果你想运行队列上的方法getAccessToAddressBook,你可以使用- addOperationWithBlock: