Objective c 从块访问时,实例变量为nil
我正在使用EventKit API获取用户的提醒。fetch API是异步完成的,当fetch完成时,可以使用一个完成块。然而,在我获取了用户的提醒之后,我将其分配给self.eventkitemrementerevents实例变量(我已经调试并发现它不是nil)。然后就在我调用一个块之后,但是从这个块的内部self.eventkitemrementerevents是nil。我真的不明白为什么会这样。也许有人可以看看我的代码,给我一个线索 我使用的API如下所示:Objective c 从块访问时,实例变量为nil,objective-c,cocoa-touch,objective-c-blocks,null,eventkit,Objective C,Cocoa Touch,Objective C Blocks,Null,Eventkit,我正在使用EventKit API获取用户的提醒。fetch API是异步完成的,当fetch完成时,可以使用一个完成块。然而,在我获取了用户的提醒之后,我将其分配给self.eventkitemrementerevents实例变量(我已经调试并发现它不是nil)。然后就在我调用一个块之后,但是从这个块的内部self.eventkitemrementerevents是nil。我真的不明白为什么会这样。也许有人可以看看我的代码,给我一个线索 我使用的API如下所示: - (void)futureR
- (void)futureReminders {
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
[self fetchReminderEventsInBackgroundFromDate:[NSDate date] withCompletionBlock:^{
// When I enter here self.eventKitReminderEvents is nil
// Which is weird because it should be set already if you look in
// fetchReminderEventsInBackgroundFromDate below...
[self processEventKitRemindersWithCompletion:^(NSArray *reminderEvents) {
// Save a copy in memory
self.futureReminderEvents = reminderEvents;
// Send a signal that indicates that this asynchronous task is completed ...
dispatch_semaphore_signal(sema);
}];
}];
// Wait for dispatch signal
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}
- (void)fetchReminderEventsInBackgroundFromDate:(NSDate *)startDate withCompletionBlock:(void(^)(void))block {
DLogName()
//NSDate *startDate = [NSDate date];
NSDate *endDate = [NSDate distantFuture]; // This will get me events 4 years from now
// Create the predicate
NSPredicate *predicate = [self.eventStore predicateForIncompleteRemindersWithDueDateStarting:startDate ending:endDate calendars:nil];
[self.eventStore fetchRemindersMatchingPredicate:predicate completion:^(NSArray *reminders) {
self.eventKitReminderEvents = reminders;
block();
}];
}
您需要创建一个selfInBlock sow,以确保不会像这样在块内丢失对self的引用
__block YourSelfClassName *selfInBlock = self;
并在块内使用selfInBlock而不是self。感谢我收到的所有答案/评论。我只是注意到我实际上设置了另一个具有相似名称的实例变量,所以它是nil
self注意:复制和粘贴代码时要非常小心:)显示代码您是如何创建实例变量的,或者它只是一个ivar?@AKV它只是一个NSArray属性-
@property(非原子,强)NSArray*eventkitemrementerevents代码>我不确定,至少试一下把它放在{and}.old-style ivars中@implementation{NSString*string;}@end
以这种方式。在调用block();)之前,您确定self.eventkitemememblerevents设置正确吗?你试过把它记录下来吗?什么?这没有道理<代码>\u块
仅当变量被分配到某个位置或在MRC中以防止块保留它时才有用。这两件事在这里都不相关。我误解了这个问题。