0

I have a unique situation with setStringValue: and hoping someone could clear this up:

Using the following theoretical example (not literal) code:

NSString *myVar;

[myOutlet setStringValue:myVar];

It appears that for any string value such as:

myVar = @"hello";

a pointer is passed to myOutlet and the NSTextField points to the same memory location as myVar, essentially making them identical. In essence:

myVar == [myOutlet stringValue];

returns TRUE.

HOWEVER

in this situation:

myVar = @"";

it seems as if it is not passing a pointer, but rather NSTextField is creating it's own independent memory location to store it's empty string, essentially:

myVar == [myOutlet stringValue];

return FALSE.

Can anyone confirm whether this is true, and if so, explain why? I believe this to be the source of a very complex problem I'm having in a piece of code I'm working on and I'm trying to wrap my mind around the root of the problem.

Thanks!

Greg Steiner
  • 647
  • 1
  • 9
  • 20

1 Answers1

2

Basically, it's pure chance that the first situation works out. These pointers are absolutely not guaranteed to be equal, and if you need to compare strings, use -isEqualToString: always.

What you're running into is probably an optimization of some sort, to avoid storing @"hello" more than once. We have no way of knowing when this will or will not happen, and it may change in the future, or from device to device.

andyvn22
  • 14,696
  • 1
  • 52
  • 74