gpt4 book ai didi

ios - 点击手势目标未保留(使用 ARC)

转载 作者:行者123 更新时间:2023-11-28 18:06:28 25 4
gpt4 key购买 nike

我创建了一个 UITapGesture,其目标不是当前对象。后来,点击时,应用程序崩溃。

View Controller .h:

@interface ViewController : UIViewController
{
IBOutlet UIImageView *iv;
}
@end

View Controller .c:

#import "ViewController.h"
#import "Target.h"

@implementation ViewController

- (void)viewDidLoad
{
[super viewDidLoad];
Target *t = [[Target alloc] init];
UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc] initWithTarget:t action:@selector(gestureDone:)];
[iv addGestureRecognizer:tgr];
[iv setUserInteractionEnabled:YES];
}

@end

目标.h:

@interface Target : NSObject

- (void)gestureDone:(UIGestureRecognizer *)gr;

@end

目标.c:

@implementation Target

- (void)gestureDone:(UIGestureRecognizer *)gr
{
NSLog(@"Gesture!");
}

@end

(我的 XIB 文件只包含一张图片...)点击图像时,它会崩溃。例如,如果我将一个实例变量 Target *t 添加到我的 View Controller (并删除 viewDidLoad 中的本地声明),则不会出现任何问题。当不这样做时,我覆盖了 Target 中的 dealloc,在那里放了一个 NSLog 并看到一旦 viewDidLoad 完成执行,Target 对象就被 fred。

我做错了什么,还是有什么问题? (通常我不会遇到这个问题,因为我使用 initWithTarget:self ...)。

最佳答案

UIGestureRecognizer 不保留其目标。大多数采用目标/ Action 对的对象不会保留它们的目标。 Cocoa Fundamentals Guide/Communicating with Objects/The Target-Action Mechanism/The Target 中提到了这一点:

Control objects do not (and should not) retain their targets. However, clients of controls sending action messages (applications, usually) are responsible for ensuring that their targets are available to receive action messages. To do this, they may have to retain their targets in memory-managed environments. This precaution applies equally to delegates and data sources.

您需要确保以其他方式保留目标,例如通过在 ViewController 的实例变量中存储对 t 的引用。

关于ios - 点击手势目标未保留(使用 ARC),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14844125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com