实例变量分配顺序冻结iOS应用程序



在我的头中,我有两个属性,如下所示。

@interface HZCalendarDataSource : NSObject
@property (strong, nonatomic) NSMutableArray *datesOnCalendar;
@property (strong, nonatomic) HZCalendarDay *currentDay;
@end

然后,在我的实现的初始值设定项中,我有以下几行代码。

- (id)init {
    self = [super init];
    if (self) {
        // Alloc / Init instance variables.
        self.datesOnCalendar = [[NSMutableArray alloc] init];
                self.currentDay = [[HZCalendarDay alloc] init];
        HZCalendarDay *date = [[HZCalendarDay alloc] initOnDate:today withEventStore:self.eventStore];
        [self.datesOnCalendar addObject:date];
        // THIS line causes the app to freeze!
        // If this line is above [self.datesOnCalendar addObject:date];
        // Then it does not freeze. Why does this happen?
        self.currentDay = date;
    }
    return self;
}

我遇到的问题是,如评论中所示,self.currentDay = date;行冻结了设备上的应用程序。但是,如果我将self.currentDay = date;行移到将日期对象添加到NSMutableArray的行之上,那么代码就可以正常工作。

所以我的问题是,为什么这件事的顺序?它应该只是将self.currentDay设置为引用我添加到NSMutableArray的相同date对象,对吗?

如果有人能向我解释一下,我会很感激,我不理解。顺序其实并不重要,所以现在我已经在将日期对象添加到数组之前移动了要执行的麻烦行,但出于教育目的,我想知道为什么这是一个问题。

编辑:

在让应用程序冻结运行一段时间后,在调用[HXCalendarDateSource setCurrentDay:]25827次后,它最终在Xcode中失败。它失败,调试器中有EXC_BAD_ACCESSS,并且-[__NSArrayM countByEnumerationWithState:objects:count:];

希望这能有所帮助。

谢谢!

所以我发现,在重新阅读错误消息后,它听起来像是由于某种原因设置器失败了,尽管我没有实现它

然而,我写了一个helper方法来循环遍历我的数组,并对与我提供的参数匹配的项执行一些操作。我调用了那个helper方法setCurrentDay:,因此我出现了命名冲突。我的代码被我写的for循环卡住了。for循环扫描了self.datesOnCalendar属性,当在将对象添加到数组之前执行self.currentDay = date;时,setCurrentDay:方法将返回,因为数组为空。在向数组添加对象后设置currentDay导致我的setCurrentDay:方法陷入循环。

修复方法是将setCurrentDay:方法重命名为与currentDay属性的setter不冲突的方法,同时调整我的for循环。

相关内容

最新更新