消息发送到 iCarousel 内 UIButton 上的已释放实例

Posted

技术标签:

【中文标题】消息发送到 iCarousel 内 UIButton 上的已释放实例【英文标题】:Message Sent To Deallocated Instance on UIButton inside iCarousel 【发布时间】:2014-07-01 08:55:56 【问题描述】:

我已经在我的 Xcode 项目中实现了 iCarousel (https://github.com/nicklockwood/iCarousel),现在有一个滚动的视图轮播。在每个视图中,我都有一个 UIButton,我添加了一个 UILongPressGestureRecogniser,如下所示:

UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] init];
[lpgr setMinimumPressDuration:1.5];
[lpgr addTarget:self action:@selector(testAction)];
[self.demoButton addGestureRecognizer:lpgr];

但是,当我点击 1.5 秒时,控制台中会显示以下错误:

2014-07-01 09:50:08.002 ExampleApp[3117:892602] -[ExampleVC testAction]:消息发送到已释放实例 0x15cd7bd20 (lldb)*

我还没有看到任何释放视图的代码部分,所以很困惑。为什么会这样,我该如何解决?

【问题讨论】:

选择器应该是testAction:而不是testAction 不,没必要 检查您的按钮以及按钮所在的视图是否仍在内存中并且尚未被释放。 我认为您应该在- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view 方法中分配Gesture,而不是其他任何地方。试试吧。 【参考方案1】:

我认为可能会有这样的问题:

UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] init];
[lpgr setMinimumPressDuration:1.5];
[lpgr addTarget:self action:@selector(testAction)];
[self.demoButton addGestureRecognizer:lpgr];

在这些行之后你忘记释放 lpgr。

[lpgr release];

如果你错过了这一行,并且由于内存优化,iCarussel 释放了演示按钮,你的手势识别器将不会被释放,并且会向释放的 demoButton 发送消息。

并像这样使用 LongPress:

[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];

和句柄:

- (void)handleLongPress:(UILongPressGestureRecognizer *)gesture

    if (gesture.state == UIGestureRecognizerStateEnded) 
        //Do Whatever You want on End of Gesture

    
    else if (gesture.state == UIGestureRecognizerStateBegan)
        //Do Whatever You want on Began of Gesture
    

别忘了实现<UIGestureRecognizerDelegate>

更新:

在每个视图中我都有一个 UIButton

您在每个视图中都有一个按钮,但是关于您的代码,我看到您有一个类变量 demobutton。因此,当您初始化视图时,添加您的演示按钮,如下所示:

    UIView* yourView ...

    UIButton* demoButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    [yourView addSubview:demoButton];

    UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] init];
    [lpgr setMinimumPressDuration:1.5];
    [lpgr addTarget:self action:@selector(testAction:)];
    [demoButton addGestureRecognizer:lpgr];

    [demoButton release];
    [lpgr release];

【讨论】:

这是否也适用于 ARC 环境? 在 ARC 中你不必发布。 (当然你不能,因为 Xcode 不允许你) 感谢您,尽管不幸的是,即使在进行了这些更改之后,崩溃仍然会发生。 您使用 ARC 还是非 Arc 编码?启用 NSZombie 有助于检测您的问题。启用使用新错误行更新您的问题后。或者发布您的整个代码,也许我可以提供更多帮助。 你能告诉我你的 - (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view 方法

以上是关于消息发送到 iCarousel 内 UIButton 上的已释放实例的主要内容,如果未能解决你的问题,请参考以下文章

将 iCarousel 与文件夹中的图像一起使用

Objective c - iCarousel 库

在应用内发送 Facebook 私人消息

如何接收发送到在 gen_server 内运行的 PID 的消息

abap 给用户发送邮件或消息(系统内)

UITableView 的 iCarousel 性能问题(iPad 主从 UI)