14

I declare the object variable as a NSString But when I use the XCode to look into my object, I saw there are two type of String, it seems that the system automatically transfer to another:

enter image description here

What are the different between them? Are they interchangeable to one and others. Also, what is the condition two change to another?

Thanks.

DNB5brims
  • 29,344
  • 50
  • 131
  • 195
  • I observed __NSCFConstantString in Xcode debugger for UILabel variable when I assigned NSString* to UILabel* by accident – sergtk Feb 11 '14 at 12:15

4 Answers4

19

They're both concrete subclasses of NSString. __NSCFString is one created during runtime via Foundation or Core Foundation, while __NSCFConstantString is either a CFSTR("...") constant or an @"..." constant, created at compile-time.

Their interfaces are private. Treat them both as NSString and you should have no trouble.

Jonathan Grynspan
  • 43,286
  • 8
  • 74
  • 104
3

As far as I know, NSCFConstantString is an implementation of NSString that keeps the string data in code memory. Compiler creates instances of it when you use @"string" constants. You can use NSCFConstantString anywhere an NSString could be used due to subclass/superclass relationship, but obviously not the other way around.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

It appears to be an optimization done by the compiler. I'm guessing that the string that is getting converted to an NSCFConstantString is equal to one of the constants that is cached for performance reasons. Your NSCFString is just a toll-free bridged string that can be an NSString or a CFString. See this article for more information.

highlycaffeinated
  • 19,729
  • 9
  • 60
  • 91
0

One of benefits of transforming NSString to NSCFConstantString is next example:

For example - in method cellForRowAtIndexPath for tableView if you will write

NSString *ident = @"identificator"; 
NSLog(@"%p", ident);

than it would be the same address for every cell. But with NSLog(@"%p", &ident) it would be different address for every cell.

NSString ident = @"identificator" is a special case - it is created as a __NSCFConstantString class so all equal string literals will share the same memory address to optimize memory usage. &ident will get an address of a local variable pointing to a NSString and will have NSString** type.

Reference to source (comments).

Community
  • 1
  • 1
Nike Kov
  • 12,630
  • 8
  • 75
  • 122