How to make a real private instance variable?

Objective CPrivateVisibilityInstance Variables

Objective C Problem Overview


I want to make an instance variable that can't be accessed from outside. Is something like that possible in objective-c? I remember Apple has private variables and stuff like that, but if people know about them, they can use them. Apple calls that "private API", but obviously others can access that stuff if they find out what's in there.

Until now I believed that something like this creates a private instance variable:

@interface MyClass : NSObject {
    CGFloat weight;
}

No @property, no @synthesize, just the declaration above.

Also I know Apple adds a _inFrontOfTheirPrivateInstanceVariables, but they said somewhere that they don't like to see others doing that because they might override accidently hidden instance variables when doing that.

What's the trick here?

Objective C Solutions


Solution 1 - Objective C

You can use the @private keyword inside the {} to make all subsequent variable declarations private. The default visibility is @protected (which is similar to protected in Java) and that generally works well. You'd have to specifically declare a variable as @public for it to be directly accessible outside the class.

This Apple documentation has further details about variable scope and visibility.

There is also a difference between "private API" and private variables. In Objective-C, you cannot make methods private — anyone can call any method. There are several ways to create "secret" methods, but that's somewhat out of the scope of this question. Here are a few related SO questions:

As far as the leading _ in front of variables, be aware that Apple also reserves this prefix for "private" methods. The best way to guarantee you avoid problems is to use normal naming conventions for your own variables and methods. However, unless you subclass something from Cocoa (other than NSObject) you can be fairly confident that you won't run into problems.

Solution 2 - Objective C

With the new LLVM Compiler available in XCode 4 and later, you can declare @private variables in default categories inside your implementation (.m) file:

@interface ClassName()
{
@private
// private variables here
}
@end

@implementation ClassName
// you can use private variables here
@end

I find this convenient, as I hate the pollution private variables bring into my header files.

Solution 3 - Objective C

You can define private methods by simply having them only in the @implementation, and not the @interface.

Similarly, you can define private instance variables inside an anonymous block at the start of the @implementation - as you do for public ivars inside the @interface.

See the following example.

@interface EXClass : NSObject
{
uint8_t publicInteger;
float publicFloat;
}

-(void)publicMethod;
@end

@implementation EXClass
{
uint8_t privateInteger;
float privatefloat;
}

-(BOOL)privateMethod {
return FALSE;
}

Remember that objective-C methods are sent as messages at runtime, though (rather than C++'s compile time binding), so respondsToSelector: would still return true and performSelector: would still call the method. The ivars would be fully private.

If you were making a library, though, theoretically no one would know about any methods you didn't declare in the header files.

Solution 4 - Objective C

All iVars in Objective-C are protected by default. If you don't write the accessor methods than other classes won't be able to see the variables.

The two exceptions are categories and subclasses.

Solution 5 - Objective C

The Apple docs for naming instance variables doesn't explicit warn against using underscore in the name of instance variables like the private method documents do.

Naming Instance Variables and Data Types

I also remember a conversation between Wil Shipley and a few other OS X developers concern the underscores. Because of the way the Obj-C compiler works, if Apple were to add a new instance variable to a class in their frameworks, it would cause all apps using those frameworks to need to be recompiled. As far as pre-existing instance variables, you should get a warning when you step on one.

Solution 6 - Objective C

I saw the following usage in a sample app (PaintGL) by Apple

In .m file

@interface MyClass (private)
  - (void) privateMethod();
  @property(...) myProperty;
@end

Disclaimer: The sample app only has method declarations, I saw the private property declaration in this SO thread

Solution 7 - Objective C

You can not make a real private instance variable. Objective-C is a dynamic language and therefore it is possible to access any variable (even @private).

My best approach:

Use it in the implementation block of you .m file. Then it is not visible and block KVC, so that KVC will not work

@implementation ClassName {
    // default to @protected
    // but the subclasses can't see ivars created in the implementation block
    float number;
}

+ (BOOL)accessInstanceVariablesDirectly {
    return NO; // no KVC
}

@end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHelloMoonView Question on Stackoverflow
Solution 1 - Objective CQuinn TaylorView Answer on Stackoverflow
Solution 2 - Objective CJohannes RudolphView Answer on Stackoverflow
Solution 3 - Objective CstefView Answer on Stackoverflow
Solution 4 - Objective CkubiView Answer on Stackoverflow
Solution 5 - Objective CcriscokidView Answer on Stackoverflow
Solution 6 - Objective CEge AkpinarView Answer on Stackoverflow
Solution 7 - Objective CBinarianView Answer on Stackoverflow