首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >CADisplayLink在iOS 6.0没有保留目标

CADisplayLink在iOS 6.0没有保留目标
EN

Stack Overflow用户
提问于 2012-09-21 14:19:20
回答 2查看 2.5K关注 0票数 3

我有这样的代码:

代码语言:javascript
运行
复制
NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(updateFrame)]];
[invocation setTarget:self];
[invocation setSelector:@selector(updateFrame)];
displayLink_ = [[CADisplayLink displayLinkWithTarget:invocation selector:@selector(invoke)] retain];
[displayLink_ setFrameInterval:1];
[displayLink_ addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

在iOS 6.0 (在5.1中,此代码工作正常),当此代码调用时,我有两个变体: EXC_BAD_ACCESS或‘调用未识别的选择器’invoke‘。似乎displayLinkWithTarget:selector: method没有保留目标。当我添加调用保留行时,代码就可以正常工作了。是iOS 6.0的错误吗?

EN

回答 2

Stack Overflow用户

发布于 2012-12-17 20:00:10

这是有用的相关信息,而不是答案.

与其使用NSInvokation,不如使用弱代理,就像我在回答这个问题时所做的那样。很简单,下面是代码:

JAWeakProxy.h:

代码语言:javascript
运行
复制
#import <Foundation/Foundation.h>

@interface JAWeakProxy : NSObject

@property (weak, nonatomic) id  target;

+ (JAWeakProxy*)weakProxyWithTarget:(id)target;

@end

JAWeakProxy.m:

代码语言:javascript
运行
复制
#import "JAWeakProxy.h"

@implementation JAWeakProxy

+ (JAWeakProxy*)weakProxyWithTarget:(id)target
{
    JAWeakProxy* newObj = [self new];
    newObj.target = target;
    return newObj;
}

- (BOOL)respondsToSelector:(SEL)sel
{
    return [_target respondsToSelector:sel] || [super respondsToSelector:sel];
}

- (id)forwardingTargetForSelector:(SEL)sel
{
    return _target;
}

@end

注意:这是ARC代码,如果不使用ARC,则需要在autorelease中使用weakProxyWithTarget:

票数 4
EN

Stack Overflow用户

发布于 2012-12-17 19:49:03

我也有同样的问题。我实际上想要一个弱引用,但由于它被记录为强引用,而且在其他版本的iOS中也是这样,所以我使用弱代理对象将选择器转发到我真正希望它去的地方。为了确保代理对象被保留,我必须想出一种方法,在iOS的坏版本中安全地保留它,而不对未损坏的版本过度保留它。我想出了一个非常优雅的单行解决方案(在解释它的四行评论之后的一行):

代码语言:javascript
运行
复制
JAWeakProxy*    weakSelf = [JAWeakProxy weakProxyWithTarget:self];
_displayLink = [CADisplayLink displayLinkWithTarget:weakSelf selector:@selector(displayLinkUpdate:)];
// Due to a bug in iOS 6, CADisplayLink doesn't retain its target (which it should and is
// documented to do) so we need to ensure a strong reference to the weak proxy object is
// created somewhere. We do this by adding it as an associated object to the display link
// which means that it gets retained for as long as the display link object is alive.
objc_setAssociatedObject(_displayLink, @"Retain the target, bitch!", weakSelf, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

记得去#import <objc/runtime.h>。使用关联对象是很棒的,因为当显示链接被dealloc编辑时,它会被释放,而在操作系统的非破坏版本上,它只是意味着显示链接保留了该对象两次。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12532377

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档