有效释放UIButton内存

时间:2016-12-08 15:43:07

标签: ios objective-c uibutton

我有以下功能可以创建自定义按钮。每次调用initKeyboard()时,都会调用14次。在我的应用程序中,用户按下一个多次调用initKeyboard的按钮。每次用户按下按钮时,我都会调用clearButtonArray()。

我注意到使用的内存逐渐增加,当它达到200MB左右时,我确实看到我的应用程序出现了一些视觉上的减速。动画不流畅等等。

我的问题是,我如何有效地释放14个按钮每次使用的内存。它看起来像clearButtonArray()没有完成这项工作。

我正在使用ARC。

感谢您的帮助。

- (void)initKeyboard:(int)scaleNo
{
    [self clearButtonArray];
    // call createGlideButton 14 times...
}

- (void)createGlideButton:(int)noteVal
                            string:(NSString *)noteStr
                            keyMod:(int)key
                         chromatic:(BOOL)chrOn
                                 x:(int)xPos
                                 y:(int)yPos
{

    GlideButton *button = [GlideButton buttonWithType:UIButtonTypeCustom];
    [button setTag:noteVal + key];
    [button setUserInteractionEnabled:YES];
    [button addTarget:self
               action:@selector(notePressedDown:withEvent:)
     forControlEvents:UIControlEventTouchDown];
    [button addTarget:self
               action:@selector(notePressedUp:withEvent:)
     forControlEvents:UIControlEventTouchUpInside];
    [button addTarget:self
               action:@selector(notePressedUp:withEvent:)
     forControlEvents:UIControlEventTouchUpOutside];
    [button addTarget:self
               action:@selector(notePressedUp:withEvent:)
     forControlEvents:UIControlEventTouchDragExit];

    [button addTarget:self
               action:@selector(notePressedUp:withEvent:)
     forControlEvents:UIControlEventTouchCancel];
    [button addTarget:self
               action:@selector(notePressedUp:withEvent:)
     forControlEvents:UIControlEventTouchDragOutside];

    UIImage *buttonbkImage = [UIImage imageNamed:@"TF8UIElements_smallKeysBtn"];
    UIImage *buttonlightImage = [UIImage imageNamed:@"TF8_smallKeysBtnBright"];
    [button setBackgroundImage:buttonbkImage forState:UIControlStateNormal];
    [button setBackgroundImage:buttonlightImage
                      forState:UIControlStateHighlighted];

    [KeyboardView addSubview:button];
    [_buttonArray addObject:button];


}

-(void)clearButtonArray
{
        for (int i=0; i < [_buttonArray count]; i++)
        {
             [[_buttonArray objectAtIndex:i] removeFromSuperview];
            [[_buttonArray objectAtIndex:i] setImage:nil forState:UIControlStateNormal];
            [[_buttonArray objectAtIndex:i] setImage:nil forState:UIControlStateHighlighted];
        }
        [_buttonArray removeAllObjects];
}

2 个答案:

答案 0 :(得分:0)

删除UIButton之前删除所有目标,以避免引用。

[[_buttonArray objectAtIndex:i] removeTarget:nil 
                   action:NULL 
         forControlEvents:UIControlEventAllEvents];

我建议您从KeyboardView一次删除它们而不是for循环。

因此,如果KeyboardView只有按钮作为子视图:

[[KeyboardView subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
[_buttonArray removeAllObjects];

答案 1 :(得分:0)

不是真的答案,但最后我在初始化时只创建了一次解开按钮,并根据我的需要更改了按钮的属性。