views:

185

answers:

4

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?

+2  A: 

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.

Benno
+1  A: 

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.

phoebus
Except that that form in the question isn't opaque. Opacity is generally achieved by using typedef'd void pointers and keeping the actual structure definition out of the public headers.
Benno
You're probably right, for some reason I assumed he was combining the code from public/private since he was talking about the private APIs.
phoebus
+5  A: 

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.

TechZen
+1  A: 

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.

NSResponder