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

标签 ios objective-c automatic-ref-counting gesture

我创建了一个 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/

相关文章:

ios - Xcode 7.0.1 - 无法识别 SDK > "iPhoneOSX.X (SDK not found)"

iOS 使用 UINavigationBar 删除输入到文本字段中的数据

ios - 自定义google登录按钮:将按钮颜色更改为红色g +登录IOS SDK

ios - 首先对 NSString 的 NSArray 按阿拉伯语字母顺序排序

objective-c - IBOutlet 是否暗示 __weak?

objective-c - 弱属性不使用 ARC 归零

ios - 我们可以在 IOS 模拟器 : 中测试 SIRIKit 扩展吗

iphone - OpenGL ES 2D - z 顺序、深度缓冲区与按顺序绘制

objective-c - 设置 NSDateComponents 会导致不正确的 NSDate

swift - 捕获列表 : reference to class instance or initialized variable?