51

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?

Quinn Taylor
  • 44,553
  • 16
  • 113
  • 131

7 Answers7

60

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.

Community
  • 1
  • 1
Quinn Taylor
  • 44,553
  • 16
  • 113
  • 131
31

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.

Johannes Rudolph
  • 35,298
  • 14
  • 114
  • 172
  • This DOES NOT work with LLVM GCC 4.2 and Xcode 4.0.2 targeting iOS 4.2. Did you mean "LLVM 2.0 compiler"? – jpswain Aug 11 '11 at 00:42
  • 3
    LLVM GCC is NOT the LLVM compiler, it's still GCC but with the LLVM parser. I meant LLVM 2.0 or LLVM 3.0 (iOS 5 Beta, XCode 4.2). – Johannes Rudolph Aug 11 '11 at 08:17
  • Ah sorry about that. It may be important though to be aware of this only working with this one compiler especially for people working on a project with others. – jpswain Aug 11 '11 at 15:42
  • You can use a `@protocol` to "hide" your instance variables from clients. – Raffi Khatchadourian Jan 14 '12 at 03:41
  • @JohanPelgrim: Ah yes, coding too much C++ I reckon – Johannes Rudolph Apr 30 '12 at 14:56
  • 1
    @RaffiKhatchadourian It's not the purpose of `@protocol`. And does not help hiding ivar from class. It just hide the whole class. And you should make your own answer entry if you want to offer an answer. – eonil Aug 20 '12 at 12:23
  • @Eonil Yes, I agree that hiding instance variable from clients is not the purpose of `@protocol`, but it would seem to answer the comment given about "polluting" header files with private variables. – Raffi Khatchadourian Aug 29 '12 at 00:19
9

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.

stef
  • 1,446
  • 1
  • 17
  • 26
  • "theoretically no one would know about any methods you didn't declare in the header files." - Not so. I've been able to write a pretty invasive Xcode plugin despite Apple's lack of documentation about their hundreds of private methods by utilizing functions from the objc_runtime.h which tell you exactly what the methods are that a class has. – ArtOfWarfare May 14 '13 at 16:26
3

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.

kubi
  • 48,104
  • 19
  • 94
  • 118
  • 5
    They will be able to interact with them through valueForKey: and setValue:forKey: however. – Jason Coco Aug 11 '09 at 20:17
  • 3
    I had no idea that KVC worked like that, thanks for posting. Turns out you can turn this behavior off by overriding `+ (BOOL)accessInstanceVariablesDirectly` to return NO. – kubi Aug 11 '09 at 21:02
2

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.

Rob Hruska
  • 118,520
  • 32
  • 167
  • 192
criscokid
  • 640
  • 1
  • 4
  • 11
  • 1
    Objective-C now allows for adding IVars to a class without affecting the subclasses (with the 2.0 language update that came with Leopard and iPhone OS 2.0) – rpetrich Aug 26 '09 at 00:39
2

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

Community
  • 1
  • 1
Ege Akpinar
  • 3,266
  • 1
  • 23
  • 29
1

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
Community
  • 1
  • 1
Binarian
  • 12,296
  • 8
  • 53
  • 84