我在 OS X 上用 Cocoa 编码。
我正在尝试接收一个拖放到我的 NSView 子类上的文件——我可以这样做;并获取其内容和文件名并显示它们- 我可以第一次对任何类型的文件执行此操作,但第二次,当我尝试拖动另一个文件时,我只能设置标题setTitle:
,但不能设置主体文本setText:
我得到的错误是:
取消拖动,因为在拖动会话期间引发了异常“NSInternalInconsistencyException”(原因“无效参数不满足:aString!= nil”)
和
-[NSTextFieldCell _objectValue:forString:errorDescription:], /SourceCache/AppKit/AppKit-1187/AppKit.subproj/NSCell.m:1532 中的断言失败
我的代码(对不起,它很长!):
- (BOOL)performDragOperation:(id<NSDraggingInfo>)sender {
NSPasteboard *pboard;
NSDragOperation sourceDragMask;
sourceDragMask = [sender draggingSourceOperationMask];
pboard = [sender draggingPasteboard];
if ([[pboard types] containsObject:NSFilenamesPboardType]) {
NSURL *file = [NSURL URLFromPasteboard:pboard];
//NSData *data = [NSData dataWithContentsOfURL:file];
NSError *error;
NSStringEncoding encoding;
NSString *contentString = [[NSString alloc] initWithContentsOfURL:file usedEncoding:&encoding error:&error];
NSLog(@"Error: %@",error);
NSString *last = [[file path] lastPathComponent];
NSArray *parts = [last componentsSeparatedByString:@"."];
NSString *filename = [parts objectAtIndex:0];
NSString *fileType = [parts objectAtIndex:1];
NSLog(@"FILETYPE: %@", fileType);
if ([fileType isEqualToString:@"txt"] || [fileType isEqualToString:@"md"]) {
[self setTitle:filename];
if (self.textViewString == (id)[NSNull null] || self.textViewString.length == 0) {
[self setText:contentString];
} else {
BOOL whatToDo = (NSRunCriticalAlertPanel(@"What do you want to do?", nil, @"Append", @"Replace", nil) == NSAlertDefaultReturn);
if (whatToDo) {
//Append
[self setText:[NSString stringWithFormat:@"%@\n%@",self.textViewString,contentString]];
} else {
//Replace
[self setText:contentString];
}
}
return YES;
} else {
return NO;
}
} else if ([[pboard types] containsObject:NSPasteboardTypeString]) {
NSString *draggedString = [pboard stringForType:NSPasteboardTypeString];
if (self.textViewString == (id)[NSNull null] || self.textViewString.length == 0) {
[self setText:draggedString];
} else {
[self setText:[NSString stringWithFormat:@"%@\n%@",self.textViewString,draggedString]];
}
return YES;
}
else {
return NO;
}
}
提前致谢!:)