gpt4 book ai didi

ios - __block 变量改变值

转载 作者:行者123 更新时间:2023-11-28 18:19:37 25 4
gpt4 key购买 nike

我正在尝试搜索提醒列表以检查是否存在提醒。方法中有一个选项可以保存提醒是否存在的值。我正在使用一个 block ,在 block 内,当找到提醒时,新值被分配给 reminderExists 变量,就像它应该的那样。但是,当我输入 save if 语句时,reminderExists 的值已从它在 block 中分配的值发生变化。我被这个问题难住了,我尝试了许多更改来诊断问题,但无济于事。感谢您的帮助!

- (BOOL)checkForReminderWithTitle:(NSString *)reminderTitle saveChanges:(BOOL)save {

NSNumber *currentGardenCurrentReminders = currentGarden.reminders;
__block NSNumber *reminderExists = [NSNumber numberWithBool:NO];

if (eventStore == nil)
{
eventStore = [[EKEventStore alloc] init];

[eventStore requestAccessToEntityType:EKEntityTypeReminder completion:^(BOOL granted, NSError *error) {

if (!granted)
NSLog(@"Access to store not granted");
}];
}


if (eventStore != nil) {

NSPredicate *predicate = [eventStore predicateForIncompleteRemindersWithDueDateStarting:[NSDate distantPast] ending:[NSDate distantFuture] calendars:[NSArray arrayWithObject:[eventStore defaultCalendarForNewReminders]]];

[eventStore fetchRemindersMatchingPredicate:predicate completion:^(NSArray *reminders) {
for (EKReminder *reminder in reminders) {

NSLog(@"%@", reminderTitle);

if ([reminder.title isEqualToString:reminderTitle]) {

reminderExists = [NSNumber numberWithBool:YES];
NSLog(@"reminder exists");
NSLog(@"after reminder exists is assigned to YES, value is %@", ([reminderExists boolValue]) ? @"True" : @"False");
if ([reminderExists boolValue]) NSLog(@"reminder exists variable works");

NSArray *alarms = reminder.alarms;

EKAlarm *alarm = [alarms objectAtIndex:0];

NSDateFormatter *nextReminderDateFormatter = [[NSDateFormatter alloc] init];
nextReminderDateFormatter.dateFormat = @"MM/dd/yyyy at hh:mm a";
NSString *nextReminderDateString = [nextReminderDateFormatter stringFromDate:alarm.absoluteDate];

NSLog(@"Next reminder is on %@", nextReminderDateString);

break;

}
}
}];

}

if (save && ([currentGardenCurrentReminders boolValue] != [reminderExists boolValue])) {

if ([reminderExists boolValue]) {
NSLog(@"within save, reminderexists == true");
} else NSLog(@"within save, reminderexists == false");

currentGarden.reminders = reminderExists;
[self.managedObjectContext save:nil];
}

return [reminderExists boolValue];

最佳答案

fetchRemindersMatchingPredicate:completion: 的调用是异步的。这意味着此调用之后的 if 语句实际上在调用 fetchRemindersMatchingPredicate:completion: 完成之前就已完成。

在执行异步处理的方法中不能有有用的返回值。您需要更改 checkForReminderWithTitle:saveChanges: 方法以返回 void 并让它传递一个完成 block ,该 block 将在调用 fetchRemindersMatchingPredicate:completion 时调用: 完成。

顺便说一句 - 为什么 reminderExists 是一个 NSNumber 指针而不仅仅是一个 BOOL

关于ios - __block 变量改变值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22976511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com