Question

I have seen many .h ( Private API's ) of apple. Most of the variables / structures / enums / classes have _ as prefix.

#import <Foundation/NSValue.h>
#import <Foundation/NSObjCRuntime.h>

@class NSString;

typedef struct _NSRange {
    NSUInteger location;
    NSUInteger length;
} NSRange;

My question is,

What is reason behind giving underscore & typedef them again with proper one?

Was it helpful?

Solution

Objective-C has a globally open name space. It's important that all names be unique. In addition to the reasons given previously, Apple reserves all underscore names for itself. This will help prevent accidental name collisions.

OTHER TIPS

It's generally used as a flag that the entity in question is private and/or internal and shouldn't be used in your code directly. I think that in older versions of C you couldn't declare an anonymous struct and so you needed a "filler" name to put there.

I believe that's in order to create an opaque type. This limits clients of the type from accessing internal details without using the provided interface. You then can use the struct through an opaque pointer, and can declare arrays, variables, etc of the type without worrying about the internal implementation, ensuring that software won't need to be recompiled if Apple decides to change the code behind such types.

For declaring structures, the style of declaring typedef struct _name {...} name goes back to the days of GCC 2.0 or so, when as was mentioned above, you couldn't have an anonymous struct.

For names of ivars, the single leading underscore is an Apple internal coding convention, and officially speaking Apple reserves all names that start with single underscores. If Apple names all their ivars that way, then you won't collide with any of their names if you don't do it.

Unfortunately, many sample code projects have been published on Apple's developer web site without going through the code and removing leading underscores on ivar names. This happens for two reasons, the main one being that developers working inside of Apple are in the habit of naming their variables that way, and the other reason is that the people reviewing sample code projects haven't really cared much about enforcing a standard coding style.

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