我对unsafe_unretained和weak关键字有一些疑问:读起来它们是完全一样的,唯一的区别是如果指向的对象被释放,weak将设置为 null。
现在我在下面的代码,它在[instanceOfTheView setDelegate:self]期间在点 [#2] 崩溃
但如果在 I4vMainView 声明 [#1] 我替换
@property (nonatomic, weak) id <I4vDraggingFileProt> delegate;
和
@property (nonatomic, unsafe_unretained) id <I4vDraggingFileProt> delegate;
它完美地工作。这种行为的原因是什么?谢谢
详细信息:使用 ARC 编译的目标 10.7。Xcode 4.5.2 。苹果 LLVM 4.1
在 I4vMainView 类中,我有:
//----------- I4vMainView.h --------
@protocol I4vDraggingFileProt <NSObject>
-(void) anURLWasDeopped: (NSURL *) droppedUrl;
@end
@interface I4vMainView : NSView <NSDraggingDestination>{
NSImageCell *imageCell;
NSImage * image;
}
@property (nonatomic, weak) id <I4vDraggingFileProt> delegate; // [#1]
在来电者中
//----------- I4vViewController.h --------
@class I4vMainView;
@protocol I4vDraggingFileProt <NSObject>
-(void) anURLWasDeopped: (NSURL *) droppedUrl;
@end
@interface I4vViewController : NSViewController <I4vDraggingFileProt>{
I4vMainView * mv;
}
-(void) anURLWasDeopped: (NSURL *) droppedUrl;
@end
//----------- I4vViewController.m --------
@implementation I4vViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Initialization code here.
}
return self;
}
- (void)loadView{
mv = [[I4vMainView alloc] init];
[mv setDelegate:self]; // <-- [#2]
[self setView:mv];
}
-(void) anURLWasDeopped: (NSURL *) droppedUrl{
// ...
}
@end
添加:
代表声明为
@property (nonatomic, weak) id <I4vDraggingFileProt> delegate;
我有这个错误
<I4vMainView: 0x10060bf40> objc[4773]: cannot form weak reference to instance (0x10061bf10) of class I4vViewController
并且回溯彻底 _objc_trap <- objc_stroreWeak <- -[I4vMainView setDelegate:] <- [I4vViewController view]