15

I was playing with the respondsToSelector method in Objective-C on MacOS-X 10.6.7 and Xcode 4.0.2, to identify if an object would respond to certain messages. According to the manuals, NSString should not respond to appendString: while NSMutableString should. Here's the piece of code which tests it:

int main (int argc, const char * argv[])
{

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    NSString *myString = [[NSString alloc] init];

    if ([myString respondsToSelector:@selector(appendString:)]) {
        NSLog(@"myString responds to appendString:");
    } else {
        NSLog(@"myString doesn't respond to appendString:");
    }

    // do stuff with myString

    [myString release];
    [pool drain];
    return 0;
}

and here's the output:

Class02[10241:903] myString responds to appendString:

I'd sort of expected the opposite. How does an NSString object respond to appendString: ? What's going on here that I'm missing ?

4
  • If you sent it a real appendString: message does anything blow up?
    – BoltClock
    May 5, 2011 at 8:55
  • 1
    Yes: Attempt to mutate immutable object with appendString:.
    – zoul
    May 5, 2011 at 8:56
  • @BoltClock: Yes it blows up, but isn't that the point of using the respondsToSelector: method, to check it won't blow up before sending it a real appendString: message?
    – user698769
    May 5, 2011 at 9:00
  • Oh my, was hitting a wall with why a NSString was saying it was mutable at run time and then would blow up - WTF Apple, this is sooo bad.
    – Joe Booth
    Apr 11, 2014 at 23:49

3 Answers 3

11

Short answer: That string is of type NSCFString, a class that inherits from NSMutableString, hence it responds to the selectors for the methods declared in NSMutableString, including superclasses.

Not so short answer: Foundation strings are toll-free bridged with Core Foundation strings. Developers use the opaque types CFStringRef (bridged with NSString) and CFMutableStringRef (bridged with NSMutableString) to refer to these strings so, at first glance, there are two different types of strings: immutable and mutable.

From a Core Foundation internal implementation perspective, there’s a private type called struct __CFString. This private type keeps a bit field that stores, amongst other information, whether the string is mutable or immutable. Having a single type simplifies implementation since many functions are shared by both immutable and mutable strings.

Whenever a Core Foundation function that operates on mutable strings is called, it first reads that bit field and checks whether the string is mutable or immutable. If the argument is supposed to be a mutable string but it in fact isn’t, the function returns an error (e.g. _CFStringErrNotMutable) or fails an assertion (e.g. __CFAssertIsStringAndMutable(cf)).

At any rate, these are implementation details, and they might change in the future. The fact that NSString doesn’t declare -appendString: doesn’t mean that every NSString instance doesn’t respond to the corresponding selector — think substitutability. The same situation applies to other mutable/immutable classes such as NSArray and NSMutableArray. From the developer perspective, the important thing is that the object that’s been returned is of a type that matches the return type — it could be the type itself or any subtype of that type. Class clusters make this a tad more convoluted but the situation is not restricted to class clusters per se.

In summary, you can only expect that a method returns an object whose type belongs to the hierarchy (i.e., either the type itself or a subtype) of the type for the return value. Unfortunately, this means that you cannot check whether a Foundation object is mutable or not. But then again, do you really need this check?


You can use the CFShowStr() function to get information from a string. In the example in your question, add

CFShowStr((CFStringRef)myString);

You should get an output similar to:

Length 0
IsEightBit 1
HasLengthByte 0
HasNullByte 1
InlineContents 0
Allocator SystemDefault
Mutable 0
Contents 0x0

where

Mutable 0

means that the string is in fact immutable.

0
2

This probably has to do with the implementation. NSString is a class cluster, which means that NSString is just a public interface and the actual implementing class is different (see what the class message gives you).

And at the same time NSString is also toll-free bridged to CFString, meaning that you can switch before those two types freely just by casting:

NSString *one = @"foo";
CFStringRef two = (CFStringRef)one; // valid cast

When you create a new string you really get a NSCFString back, a thin wrapper around CFString. And the point is that when you create a new mutable string, you also get an instance of NSCFString.

Class one = [[NSString string] class]; // NSCFString
Class two = [[NSMutableString string] class]; // NSCFString

I guess this was convenient from the implementation point of view – both NSString and NSMutableString can be backed by a common class (= less code duplication) and this class makes sure you don’t violate the immutability:

// “Attempt to mutate immutable object with appendString:”
[[NSString string] appendString:@"foo"];

There’s a lot of guess work in this answer and I don’t really understand the stuff, let’s hope somebody knows better.

1

You should not make assumptions about a method being not there. That method might be used internally or for whatever reason it exists. Technically, it's just private API.

You only have a contract to the public declarations (docs), and they don't show that message. So be prepared to get into trouble rather quickly if you use other features.

2
  • Agreed, but one could argue that supporting a method only to throw an exception is weird. It goes against duck typing – this particular thing walks like a duck, but isn’t really a duck.
    – zoul
    May 5, 2011 at 9:08
  • @zoul: I've seen NotImplementedExceptions thrown all over the place in other languages. I wouldn't be surprised if something similar happened here. But your answer seems more sensible.
    – BoltClock
    May 5, 2011 at 9:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.