Question

After updating Xcode to version 5.1, I had a warning that told me I had defined a constant that I wasn't using. Its definition looked like this:

static NSInteger const ABCMyInteger = 3;

I was happy to see that it got marked, because I thought this meant that the compiler was now able to check for unused constants in addition local to variables.

I refactored some more, making three NSString constants obsolete. All three were defined very similarly to the NSInteger from above:

static NSString *const ABCMyString = @"ABCMyString";

To my surprise, however, these do not get marked as "unused", though I know for sure that they aren't used anymore.

Can someone explain why an NSInteger does get noticed by the compiler as unused, but an NSString does not?

Was it helpful?

Solution

A primitive variable is just a memory block allocated in a static memory part and initialized by the compiler. The string object, however, is a variable initialized at runtime (in startup, probably), so the compiler adds an implicit call to the constructor and uses the variable as a parameter for that call. So the variable is being used.

The _unused item of the structure is IMHO not a directive, but just a member variable, probably it is added for better alignment (fills the object size to a round size).

OTHER TIPS

The definition of an NSString literal at compile time rely on the use of the NSSimpleCString meta class. This class looks something like this:

@interface NSSimpleCString : NSString {
@package
    char *bytes;
    int numBytes;
#if __LP64__
    int _unused;
#endif
}
@end

@interface NSConstantString : NSSimpleCString
@end

The addition of the _unused flag make me believe that further down the implementation of NSSimpleCString the code will instruct the compiler to silence those warnings with __unused.
You can try yourself by prepending your integer or float constant with __unused like:

__unused static const NSInteger ABCMyInteger = 3;

For a more in depth explanation read the article on literals by Mike Ash

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top