What is @private? and what is its use?

I see the code in one of my @private projects ..

@interface mapview : UIViewController<CLLocationManagerDelegate, MKMapViewDelegate,UITextFieldDelegate> { @private CLLocationManager *_locationManager; MKReverseGeocoder *_reverseGeocoder; MKMapView* _mapView; } 

what it is?

I know, maybe this is a very low question ... I want to know the use of @private here.

+4
source share
3 answers

@private limits the scope or "visibility" of instance variables declared in accordance with the @private directive. The compiler (presumably) applies this scope and does not allow direct access to private instance variables outside the class that declares them . In modern versions of Objective-C (64-bit in OS X or iOS 4 or higher), instance variables should not be declared in the @interface class, and visibility is not a problem. In outdated time series, instance variables had to be declared in @interface , so @private was the only way to prevent client code from directly using instance variables.

See the Objective-C Language Guide for more details (including @public , @protected and @package visibility modifiers).

GCC does not provide visibility, but I believe that Clang 2.0 will be.

+4
source

This means that these instance variables are considered to be 'private' to the class and should not be directly accessible (which is hardly ever done in Obj-C, as it is so dynamic and Cocoa provides you with so many free, generated accessories). So this means that you cannot do something like this:

 mapview* myMapView = [[mapview alloc] initWithNibName:nil bundle:nil]; CLLocationManager* myMapViewsLocationManager = myMapView->_locationManager; // NO!! 

Since the variable is private, the above should not work (note that the compiler actually resolves this at the moment, but you get a warning that someday it will not ... and I think that the clang 2.0 compiler may actually generate a hard error )

+2
source

@private is a visibility modifier. The variable, which is @private, can only be visible and used inside the class in which it is defined.

@public will allow other classes to view and modify this variable.

+1
source

Source: https://habr.com/ru/post/1336265/


All Articles