Objective-C库-无法形成对类实例的弱引用
我目前正在使用Objective-C的XMPP库,并使用“桌面”示例代码 它登录良好;然而,当我打开一个新的聊天室,或者有人给我发信息时,它崩溃了 这似乎是出问题的地方:Objective-C库-无法形成对类实例的弱引用,objective-c,osx-lion,Objective C,Osx Lion,我目前正在使用Objective-C的XMPP库,并使用“桌面”示例代码 它登录良好;然而,当我打开一个新的聊天室,或者有人给我发信息时,它崩溃了 这似乎是出问题的地方: XMPPStream[11678:1b03] RECV: 2012-06-05 15:03:59:379 XMPPStream[11678:1b03] RECV: 2012-06-05 15:03:59:382 XMPPStream[11678:403] RosterController: xmppRosterDidCha
XMPPStream[11678:1b03] RECV:
2012-06-05 15:03:59:379 XMPPStream[11678:1b03] RECV:
2012-06-05 15:03:59:382 XMPPStream[11678:403] RosterController: xmppRosterDidChange:
2012-06-05 15:03:59:387 XMPPStream[11678:403] RosterController: xmppRosterDidChange:
2012-06-05 15:04:01:900 XMPPStream[11678:403] tableView:shouldEditTableColumn:"jid" row:0
2012-06-05 15:04:01:900 XMPPStream[11678:403] user:
objc[11678]: cannot form weak reference to instance (0x7fcd4a498930) of class ChatController
及
“不能对ChatController类的实例…形成弱引用”是什么意思?你们知道我怎么修吗?我在雪豹上使用了这个代码的旧版本,它成功了,狮子把我搞砸了
谢谢大家! 看着,我发现了一个有趣的段落:
ARC对弱引用进行归零的实现需要关闭
Objective-C参考计数系统和
调零弱参考系。这意味着任何
覆盖保留和释放不能成为归零弱者的目标
参考资料。虽然这种情况并不常见,但一些Cocoa类,如NSWindow,
受此限制。幸运的是,如果你击中其中一个
在这种情况下,您将立即知道它,因为您的程序将因错误而崩溃
信息如下:
objc[2478]: cannot form weak reference to instance (0x10360f000) of class NSWindow
如果您真的必须对这样的类进行弱引用,那么
可以使用_unsafe_unretained限定符代替_weak
你是否在应用程序中打开了ARC?如果你关闭它,你会得到更好的结果吗?记住,你需要对两个地方进行注释
@interface GCDMulticastDelegateNode : NSObject
{
//#if __has_feature(objc_arc_weak)
//__weak id delegate;
//#else
__unsafe_unretained id delegate;
//#endif
dispatch_queue_t delegateQueue;
}
- (id)initWithDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue;
//#if __has_feature(objc_arc_weak)
//@property (/* atomic */ readwrite, weak) id delegate;
//#else
@property (/* atomic */ readwrite, unsafe_unretained) id delegate;
//#endif
@property (nonatomic, readonly) dispatch_queue_t delegateQueue;
@end
在我的项目中(作为一个错误),在dealoc
中对self
的引用很弱(这是一个单独的方法,用于清除已使用的资源)。
使用对此对象的一个属性的弱引用(仅捕获对资源的引用)解决了问题
在dealloc
中创建对半破坏对象的弱引用确实很奇怪
千万不要这样写:
@interface GCDMulticastDelegateNode : NSObject
{
//#if __has_feature(objc_arc_weak)
//__weak id delegate;
//#else
__unsafe_unretained id delegate;
//#endif
dispatch_queue_t delegateQueue;
}
- (id)initWithDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue;
//#if __has_feature(objc_arc_weak)
//@property (/* atomic */ readwrite, weak) id delegate;
//#else
@property (/* atomic */ readwrite, unsafe_unretained) id delegate;
//#endif
@property (nonatomic, readonly) dispatch_queue_t delegateQueue;
@end
- (void) dealloc
{
[self freeUsedResource];
}
- (void) freeUsedResource
{
__weak MyClass *weakSelf = self;
dispatch_async(self.queue, ^{
[weakSelf.usedResource freeUsedMemory];
});
}