这段代码会随机导致我的应用程序崩溃吗?
for(UIView *view in [_scrollView subviews]) {
NSMutableArray *_mutableArray = [_array mutableCopy];
[_mutableArray filterUsingPredicate:[NSPredicate predicateWithFormat:@"guid like %@",view.object.guid]];
if([_mutableArray count] != 0) {
//object is already on screen we need to update it
[view setObject:(Object*)[_mutableArray objectAtIndex:0]];
}
else {
//object not on screen add it
_mutableArray = [_array mutableCopy];
[_mutableArray filterUsingPredicate:[NSPredicate predicateWithFormat:@"guid not like %@",view.object.guid]];
UIView *newView = [[UIView alloc] initWithObject:(Object*)[_mutableArray objectAtIndex:0]];
[_scrollView addSubview:newView];
}
}
正如您所看到的,此方法更新屏幕上的对象,如果对象不在屏幕上,则会创建该对象并将其添加到滚动视图子视图层次结构中。 现在我担心的是我在枚举它时修改了滚动视图子视图层次结构。这最终会让我的应用程序崩溃吗?
如果是,如何修改上述代码才能安全并实现相同的功能?
谢谢!
for(UIView *view in [_scrollView subviews]) {
NSMutableArray *_mutableArray = [_array mutableCopy];
[_mutableArray filterUsingPredicate:[NSPredicate predicateWithFormat:@"guid like %@",view.object.guid]];
if([_mutableArray count] != 0) {
//object is already on screen we need to update it
[view setObject:(Object*)[_mutableArray objectAtIndex:0]];
}
else {
//object not on screen add it
_mutableArray = [_array mutableCopy];
[_mutableArray filterUsingPredicate:[NSPredicate predicateWithFormat:@"guid not like %@",view.object.guid]];
UIView *newView = [[UIView alloc] initWithObject:(Object*)[_mutableArray objectAtIndex:0]];
[_scrollView addSubview:newView];
}
}
As you can see this method updates the objects that are on screen and if an object is not on screen it is created and added to the scrollView subview hierarchy.
Now my concern is that I'm modifying the scrollView subviews hierarchy while enumerating it. Will this crash my app eventually?
If yes, how can I modify the above code to be safe and achieve the same functionality?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许。在这种特殊情况下,答案在于 UIScrollView 如何返回其子视图列表。如果它从子视图列表中创建一个副本或一个新数组并返回它,那么不,它不会崩溃。如果它返回相同的数组,稍后当您 addSubview: 时它会更新,那么您就是在玩火。
除非另有说明,否则改变您正在枚举的集合是一个坏主意。首先复制它并枚举它。
Perhaps. The answer in this particular case would be in how UIScrollView returns its list of subviews. If it makes a copy or a new array from it's list of subviews and returns that, then no, it won't crash. If it returns the same array it'll later update when you addSubview:, then you're playing with fire.
Unless it's documented otherwise, mutating a collection you're enumerating is a bad idea. Make a copy of it first and enumerate that instead.