开发者

Variable mysteriously being changed

So, this is something of a followup to my previous question. I'm running into an odd bug, and can't figure out whats wrong. Essentially, I wrote the following code to detect when text was entered in a text box, and change the variables accordingly:

-(void)controlTextDidChange:(NSNotification *)aNotification
{
    NSTextView *fieldEditor = [[aNotification userInfo] objectForKey:@"NSFieldEditor"];

    if ([[aNotification object] isEqualTo:[self idField]])
    {

        [self setIdNumber:[[fieldEditor textStorage] string]];
    }
    else if ([[aNotification object] isEqualTo:[self chapterField]])
    {

        [self setChapterNumber:[[fieldEditor textStorage] string]];

    }

}

This takes the entered text, checks which text box is being edited, and chang开发者_Go百科es a variable depending on which box is edited. The problem is that "else if.." block of code changes both the variables chapterNumber and IdNumber to the entered text, even though there is only code for changing chapterNumber. I just can't figure out whats wrong...


You were experiencing this problem because your two setter methods setIdNumber: and setChapterNumber: aren't copying the string that's in the field editor, but just pointing at it.

The field editor, as you may know, is an NSTextView which is reused by whichever text field happens to have focus at the moment. It's always the same object, and that object's string is changed depending on what text field it's attached to.

When you assign a variable to the field editor's string, you are assigning a pointer; whatever variable you're assigning now has the address of that string. Since the field editor is always the same object, the address of the string stays the same even if the contents change, and so any pointer that you have -- any variable to which you've assigned that string -- will appear to change its value.

If you make a new string using the contents of the field editor's string, using copy or stringWithString: or some other means, then you get a new object, at an address that the field editor can't change, and each variable to which you have assigned such a copy will continue to yield the value in the copied string no matter what happens to the field editor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜