开发者

setString vs. setStringValue in Cocoa

I tried to use the method setString to change the text in a textfield and it didn't work. Then I开发者_开发技巧 changed it to setStringValue and it worked. So what is setString used for?


NSTextField does not have a setString: method. NSTextField is a type of NSControl, and NSControl has a setStringValue: method.

NSText and its more famous subclass NSTextView have a setString: method. @John Boker is correct that the field editor is an NSText, but you still can't send setString: to an NSTextField, even in edit mode. You'd need to get the field editor from the window and then call setString: on that (not that you really should do that).

While it is confusing to newcomers, there is a good rationale behind the different methods. NSControl has a "value", and that value can take different types (setDoubleValue:, setObjectValue:, etc.) This allows me to set the value as a double, but then retrieve in as a string. For the broad range of possible controls, this makes good sense and is very flexible. NSText is not a control; note how it doesn't have setAction: or setTarget: either. Its purpose is to display and edit (attributed) strings. When you call string, you are actually getting the real backing text storage, not just the value of the object in string form (as stringValue does for NSControl).

That said, when you say "it didn't work," I hope you mean that you got a compiler warning about this that told you that NSTextField may not respond to setString:. If you're ignoring compiler warnings, then you're going to have a lot of problems in ObjC.


from: http://macosx.com/forums/software-programming-web-scripting/43905-_outlet-setstring-testing-selector-not-recognized.html#5

setString: is for NSText, which is the class used for an NSTextField's field editor while it is being edited, and for the NSText subclass NSTextView which can display and edit styled text as in TextEdit.

So the way i take it is you can only use setString: when the field is in an edit mode, i think.


Going a bit more generically (in contrast to my comment on Rob's answer):

Objects respond to messages. You can send a message to any object that responds to that message; you can't send a message to any object that doesn't respond to it.

Instances of NSText and its subclass NSTextView respond to setString:, so you can send NSText objects and NSTextView objects setString: messages.

Instances of NSControl and its subclasses, including NSTextField, respond to setStringValue:, so you can send NSControl objects, NSTextField objects, and other control objects setStringValue: messages.

See Rob's answer and my comment on it for why these two specific branches of the class hierarchy have these seemingly-similar-but-differently-named methods.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜