gpt4 book ai didi

objective-c - __unsafe_unretained 与弱 : crash during setDelegate

转载 作者:行者123 更新时间:2023-12-03 16:37:50 25 4
gpt4 key购买 nike

我对 unsafe_unretainedweak 关键字有一些疑问:读起来它们是完全相同的,唯一的区别是 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

添加:

委托(delegate)声明为

@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]

enter image description here

最佳答案

我找到了答案:如 weak property for delegate cannot be formed 中所述

You cannot currently create zeroing-weak references to instances of the following classes (emphasis mine):

NSATSTypesetter, NSColorSpace, NSFont, NSFontManager, NSFontPanel, NSImage, NSMenuView, NSParagraphStyle, NSSimpleHorizontalTypesetter, NSTableCellView, NSTextView, NSViewController, NSWindow, and NSWindowController. In addition, in OS X no classes in the AV Foundation framework support weak references.

For declared properties, you should use assign instead of weak; for variables you should use __unsafe_unretained instead of __weak.

In addition, you cannot create weak references from instances of NSHashTable, NSMapTable, or NSPointerArray under ARC.

关于objective-c - __unsafe_unretained 与弱 : crash during setDelegate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13845234/

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