我有一些简短的iOS Objective-C示例代码(从较大的项目简化),导致我无法解释的NSUndoManager崩溃。
也就是说,当仅由NSUndoManager保留的对象进行释放时(因为它超出了undo级别),并且根据docs调用removeAllActionsWithTarget:self
的要求,我得到了EXC_BAD_ACCESS。
// SimpleViewController.m
@interface ViewController ()
@property (nonatomic, strong) NSUndoManager *undoManager;
@end
@implementation ViewController
@synthesize undoManager;
// called from a simple button
- (IBAction)doItTapped:(id)sender
{
CoolObject *object = [CoolObject new];
object.undoManager = self.undoManager;
// according to docs, object will be retained by NSUndoManager here
// but target will not (which should be okay)
[self.undoManager registerUndoWithTarget:self selector:@selector(notCool:) object:object];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.undoManager = [NSUndoManager new];
self.undoManager.levelsOfUndo = 3;
}
和
// CoolObject.m
@implementation CoolObject
- (void)dealloc
{
[self.undoManager removeAllActionsWithTarget:self];
}
@end
第四次点击按钮(
levelsOfUndo
+ 1)后,它崩溃。如果我将NSUndoManager与GCUndoManager交换,则不会崩溃。
在iOS 10.2 SIM和设备中测试。
感谢您的任何想法!
最佳答案
由于您在使用self.undoManager
的那一刻未保留ojit_code,因此他们很可能会收到此错误。当对象已经被释放并尝试访问它时,您将获得错误的访问异常。
尝试从此更改代码:
CoolObject *object = [CoolObject new];
对此:
@interface ViewController (){
CoolObject *object;
}
@property (nonatomic, strong) NSUndoManager *undoManager;
@end
@implementation ViewController
- (IBAction)doItTapped:(id)sender
{
object = [CoolObject new];
object.undoManager = self.undoManager;
// according to docs, object will be retained by NSUndoManager here
// but target will not (which should be okay)
[self.undoManager registerUndoWithTarget:self selector:@selector(notCool:) object:object];
}
@end
希望这会有所帮助。
关于ios - NSUndoManager removeAllActionsWithTarget崩溃,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41602669/