iOS – 一次不分配太多的内存

试图绕过一些iOS设备上发生的崩溃,并结合苹果的build议“不会导致分配高峰”。 我怎样才能改变这个代码不会一次发生?

for (Item *item in self.items) { ItemView *itemView = [[ItemView alloc] initWithFrame:CGRectMake(xPos, kYItemOffsetIphone, kItemWidthIphone, kItemHeightIphone) ]; itemView.delegate = self; [itemView layoutWithData:item]; //this just adds an imageView and button [self.scrollView addSubview:itemView]; xPos += kXItemSpacingIphone; } 

self.items数组中有大约20个对象,用于构build20个ItemView。 再一次,有没有办法让这个代码更“分配密集”?

我亲自做一些事情:

  1. 让我的视图控制器的滚动视图的delegate (如果你在代码中这样做,你必须修改你的视图控制器的.h来说,它符合UIScrollViewDelegate )。

  2. 定义一个scrollViewDidScroll方法,该方法(a)确定滚动视图的可见部分的框架; (b)确定哪个子视图与该可见部分相交; (c)加载可见的项目,并卸载那些不可见的项目。

所以,例如,它可能看起来像下面这样:

 - (void)scrollViewDidScroll:(UIScrollView *)scrollView { // Determine the frame of the visible portion of the scrollview. CGRect visibleScrollViewFrame = scrollView.bounds; visibleScrollViewFrame.origin = scrollView.contentOffset; // Now iterate through the various items, remove the ones that are not visible, // and show the ones that are. for (Item *itemObject in self.itemCollection) { // Determine the frame within the scrollview that the object does (or // should) occupy. CGRect itemObjectFrame = [self getItemObjectFrame:itemObject]; // see if those two frames intersect if (CGRectIntersectsRect(visibleScrollViewFrame, itemObjectFrame)) { // If it's visible, then load it (if it's not already). // Personally, I have my object have a boolean property that // tells me whether it's loaded or not. You can do this any // way you want. if (!itemObject.loaded) [itemObject loadItem]; } else { // If not, go ahead and unload it (if it's loaded) to conserve memory. if (itemObject.loaded) [itemObject unloadItem]; } } } 

这是基本的想法。 你当然可以根据你的应用程序的特定devise来优化这个逻辑,但这就是我通常所做的。