iOS - 不会一次分配太多内存

时间:2012-10-10 19:05:33

标签: ios memory-management uiview

尝试绕过某些iOS设备上发生的崩溃,并结合Apple的建议“不会导致分配峰值”。如何将此代码更改为不会立即发生?

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个对象,用于构建20个ItemView。再次,有没有办法让这个代码减少“分配密集”?

1 个答案:

答案 0 :(得分:1)

我个人做的事情是:

  1. 使我的视图控制器成为滚动视图的delegate(如果您在代码中执行此操作,则必须修改视图控制器的.h以表示它符合UIScrollViewDelegate)。

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

  3. 因此,例如,它可能类似于以下内容:

    - (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];
            }
        }
    }
    

    这是基本的想法。您当然可以根据应用程序的特定设计优化此逻辑,但这就是我通常的做法。