JohnnyHunter
JohnnyHunter

Reputation: 388

Variables inside extensions in objective-c

I want to know how the odometer variable behaves in the following example.I mean since its declared within an extension is it private?

 //In Car.m
#import "Car.h"
@interface Car ()
@property (readonly) double odometer;
-(BOOL)engineIsWorking;
@end

Upvotes: 0

Views: 71

Answers (2)

Guillaume Algis
Guillaume Algis

Reputation: 11016

Yes. As your are declaring the extension in you .m file, and you never #import this .m file anywhere (you #import the .h), only the code within the .m file has access to this extension.

As stated in the docs:

Class extensions are often used to extend the public interface with additional private methods or properties for use within the implementation of the class itself.

Upvotes: 1

bbum
bbum

Reputation: 162712

The variables/methods declared in the extension are only visible in the compilation units that they are imported into or declared within.

For example, you could put your extensions in a file called Car_Private.h, then #import "Car_Private.h" in both Car.m (so the @implementation Car automatically synthesizes storage and methods) and Tire.m. By doing so, Tire.m would effectively have access to engineIsWorking and odometer.

That is, extensions are only as "private" as you want them to be. Note that nothing is truly private in Objective-C; it is only private at compilation time.

Upvotes: 2

Related Questions