这让我有点疯狂..
下面是迄今为止我的程序的屏幕截图。
右边是一个 NSTableView(基于 View )。用户可以在此处选择他们想要处理的文档。
左边是 NSTextView。文本的显示取决于他们在 NSTableView 中选择的项目。
还有大的加号和减号按钮,用于在表格 View 中创建/删除新项目。
简单吧?我希望如此。
现在我有了它,所以 TableView 从可变数组中获取数据。可变数组包含名为 DocumentItem 的类的对象。 DocumentItem 只有两个字符串,一个用于文档文本,一个用于文档标题。
到目前为止有效的方法:
当我使用代码手动将对象添加到数组时,我可以自由切换文档,并且 TextView 也会相应更新。
什么不起作用:
当用户切换到不同的文档时,我想调用 NSTableView replaceObjectAtIndex
方法保存他们对数组中的对象所做的更改。
到目前为止我的代码是如何工作的:
可变数组存储在数据类中。数据类是一个共享类,在我的代码中称为 theDATA。
我的类中有一个具有 TextView 的线程循环。在我的 TableView 类中,我有一个名为blastToScreen的方法,它将把名为shouldBLAST的BOOL更改为YES。
这是我的 TableController 类中将 BOOL 设置为 YES 的代码:
- (void) blastToScreen{
theDATA.blasttext = [[theDATA.globaldoclist objectAtIndex:[tablevieww selectedRow]] doccontents];
theDATA.shouldBLAST=YES;
}
这是我的循环线程中的shouldBLAST方法(在与textview不同的类中)。请注意,if 语句的 if(theDATA.switchedrow)
是为了确保仅当用户在 TableView 中切换其行时才运行某些代码。
if(theDATA.shouldBLAST){
if(theDATA.switchedrow){
DocumentItem * itemr = [theDATA.globaldoclist objectAtIndex:theDATA.lastindex];
NSLog(@"(%li) prev content - >%@",(long)theDATA.lastindex,itemr.doccontents);
itemr.doccontents=textvieww.string;
NSLog(@"(%li)adding content - > %@ <- to %@",theDATA.lastindex, itemr.doccontents,itemr.docname);
theDATA.switchedrow=NO;
[theDATA.globaldoclist replaceObjectAtIndex:theDATA.lastindex withObject:itemr ];
NSLog(@"changed: - > %@",[[theDATA.globaldoclist objectAtIndex:theDATA.lastindex] doccontents]);
}
textvieww.string=theDATA.blasttext;
theDATA.shouldBLAST=NO;
NSLog(@"changed: - > %@",[[theDATA.globaldoclist objectAtIndex:theDATA.lastindex] doccontents]);
theDATA.lastindex=theDATA.selectedrow;
}
这是关于这一切的奇怪部分:
根据我设置的 NSLog 语句,我的代码会工作一瞬间,然后重置。
下面是控制台的内容。忽略 (0)。这只是谈论最后选择的索引。
它的意思是切换之前的文本什么都没有(很好)。据说它正在将文本“Potato”添加到该数组中(仍然没问题)。然后,我第一次从数组中获取对象时,它显示它成功更改为“Potato”(仍然很好)。然后,当我尝试在几行后获取相同的确切数据时,它什么也没返回。 :(
我觉得问题出在我的 TableController 类中的某个地方。 Here's a link到我的 TableController 类中的代码。
这是控制台返回的内容:
2015-09-14 17:17:46.024 Simplicity[4801:432580] (0) prev content - >
2015-09-14 17:17:46.025 Simplicity[4801:432580] (0)adding content - > Potato <- to Untitled
2015-09-14 17:17:46.025 Simplicity[4801:432580] changed: - > Potato
2015-09-14 17:17:46.025 Simplicity[4801:432580] changed: - >
我真的希望你们能帮助我。我几乎尽了一切努力来解决这个问题。这阻碍了我完成我的软件。
最佳答案
很可能,您的 DocumentItem
类的 doccontents
属性应该是 strong
(或 retain
) 复制
。
来自docs for the string
property of NSText
(NSTextView
继承自):
For performance reasons, this method returns the current backing store of the text object. If you want to maintain a snapshot of this as you manipulate the text storage, you should make a copy of the appropriate substring.
因此,如果您只是保留对同一对象的引用,那么当 TextView 的内容更改时,您引用的对象的内容也会更改。您需要制作一份私有(private)副本。
关于objective-c - NSTableView + NSTextView = 灾难 :(,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32574282/