Как присвоить значение переменной из свойства объекта в Objective-C?
В строке /*1*/ объявляю переменную identifier.
В строке /*2*/ пытаюсь присвоить ей значение из notification.request.identifier.
В строке /*3*/ переменная identifier имеет значение nil.
Что я делаю не так и как сделать правильно? К сожалению почти впервые вижу Objective-C.
В строке /*2*/ notification.request.identifier точно имеет значение отличное от nil;
if([UNUserNotificationCenter currentNotificationCenter] != nil){
/*1*/ __block NSString *identifier;
[[UNUserNotificationCenter currentNotificationCenter] getDeliveredNotificationsWithCompletionHandler:^(NSArray<UNNotification *> * _Nonnull notifications) {
for (UNNotification *notification in notifications) {
if ([notification.request.content.userInfo[@"id"] isEqualToString:notificationId]) {
/*2*/ identifier = notification.request.identifier;
}
}
}];
/*3*/ if (identifier != nil) {
[[UNUserNotificationCenter currentNotificationCenter] removeDeliveredNotificationsWithIdentifiers:@[identifier]];
}
}
Ответы (1 шт):
Автор решения: schmidt9
→ Ссылка
Метод getDeliveredNotificationsWithCompletionHandler: выполняется асинхронно, поэтому строка 3 выполняется раньше, чем 2. Поэтому ваш код можно переписать так (я еще убрал ненужные проверки на nil)
[[UNUserNotificationCenter currentNotificationCenter] getDeliveredNotificationsWithCompletionHandler:^(NSArray<UNNotification *> * _Nonnull notifications) {
for (UNNotification *notification in notifications) {
if ([notification.request.content.userInfo[@"id"] isEqualToString:notificationId]) {
/*2*/
NSString *identifier = notification.request.identifier;
/*3*/
[[UNUserNotificationCenter currentNotificationCenter] removeDeliveredNotificationsWithIdentifiers:@[identifier]];
break;
}
}
}];