0

I'm trying to do something very simple in a Mac app, with a frustrating problem.

I have a NSPopUpButton with 5 items, a NSTextView, and a NSMutableArray with five strings. When the popupbutton selection is changed, the corresponding string is displayed in the text view. When the text view text changes, the corresponding string in the array is also changed.

Some code:

In init code:

self.array = [NSMutableArray arrayWithObjects:@"string 1", @"string 2", @"string 3", @"string 4", @"string 5", nil];

In view body:

-(void)popUpChanged:(id)sender {
    NSInteger index = [sender indexOfSelectedItem];

    NSString *string = [self.array objectAtIndex:index];
    self.textView.string = string;
    NSLog(@"Selected string: %@", string);
}

-(void)textDidChange:(NSNotification *)notification {
    NSInteger selectedSegment = self.popUp.indexOfSelectedItem;
    NSText *newText = notification.object;
    [self.array replaceObjectAtIndex:selectedSegment withObject:newText.string];
    NSLog(@"New string: %@", newText.string);
}

Problem: PopUp item 0 is selected, "string 1" is displayed in textView.

TextView is changed to "string 100"

PopUp item 4 is selected, "string 5" is displayed in textView.

PopUp item 0 is selected again. TextView shows "string 5", but should show "string 100".

(NSLogs show that the string is correctly changed in textDidChange: but that it has been changed to "string 5" in popUpChanged:)

What is going on?

4

1 回答 1

1

NSText的方法状态的文档string(强调添加):

出于性能原因,此方法返回文本对象的当前后备存储。如果您想在操作文本存储时保留此快照,则应制作相应子字符串的副本。

这意味着您放置在数组中的对象会不断更新并跟踪文本视图的内容。

尝试:

[self.array replaceObjectAtIndex:selectedSegment withObject:newText.string.copy];
于 2013-10-17T00:22:36.883 回答