All my research shows that there’s no real usage for the @private directive – so I must be missing something and need you experts to chime in ๐
Assume we have 2 classes: a Car class and a SportsCar class, where SportsCar is a subclass of Car.
Here’s the Car class:
@interface Car : NSObject {
NSString *make;
NSString *model;
@private
int numberOfBackSeatPassengers; // I'm making this a private iVar cause I'm just gonna
// say that all Sportscars will be 2-seaters and therefore shouldn't
// be able to set/get the number of back-seat passengers
}
@property (nonatomic, strong) NSString *make, *model;
// Now here's my first issue: if I also make "numberOfBackSeatPassengers" an @property
// then it seems like all subclasses of this Car class *WILL* be able to access it as
// well - even though I declared it as @private - but I'll do this anyway to make my point:
@property int numberOfBackSeatPassengers;
@end
The Implementation looks like this:
@implementation Car
@synthesize make, model, numberOfBackSeatPassengers;
@end
Now here’s the Sportscar class:
#import "Car.h"
@interface Sportscar : Car
@property int turboEngineSize;
@end
And its implementation:
#import "Sportscar.h"
@implementation Sportscar
@synthesize turboEngineSize;
@end
In “main” I have this:
Car *car1 = [[Car alloc] init];
[car1 setMake:@"Chevy"];
[car1 setModel:@"Impala"];
[car1 setNumberOfBackSeatPassengers:3];
Sportscar *sports1 = [[Sportscar alloc] init];
[sports1 setMake:@"Audi"];
[sports1 setModel:@"tt"];
[sports1 setNumberOfBackSeatPassengers:3];
Obviously I’m able to set the NumberOfBackSeatPassengers on the Sportscar – even though that iVar was declared as @private – but that’s because I made it an @property in “Car.h” which means that the synthesized getter and setter for it are Instance Methods, thereby available to all subclasses of Car.
The other option would have been to NOT declare numberOfBackSeatPassengers as an @property in “Car.h”, keep it there as only a simple iVar, and instead manually create a Setter and Getter for it in the @implementation of “Car.m” like this:
-(void) setNumberOfBackSeatPassengers:(int)numPassgeners {
numberOfBackSeatPassengers = numPassgeners;
}
-(int)numberOfBackSeatPassengers {
return numberOfBackSeatPassengers;
}
This would have made the getter and setter for numberOfBackSeatPassengers available only within “Car.m” – which I suppose would make them “private” – but they’d be too private: I could never call them from Main, or from anywhere outside of “Car.m” Moreover, and this is the real point: doing it this way means the @private directive back in “Car.h” doesn’t really come into play at all in any of this. I mean I could now go back to “Car.h”, take out the “@private” directive there — and my manual setter and getter for numberOfBackSeatPassengers would still work exactly the same as they are now, being supposedly private – so what’s to be gained with “@private”? How does it truly come into play?
Can anyone shed any real light on this?
(And yes, I know I can extend my Car class in the @interface section of the “Car.m” file – through a category, or make numberOfBackSeatPassengers a readonly property first, then change it to readwrite, etc. – but these all seem like workarounds or “hacks” to making “@private” work. I just don’t get how @private truly works on its own.)
=====================================================
EDIT – in response to aroth’s comments below:
1) aroth’s absolutely correct in saying that a subclass could still theoretically call a method that was NOT declared in its parent class’s Header — by using performSelector. I say “theoretically”, cause in my case its not quite working correctly: if – in “main” – I call
[sportscar1 performSelector:@selector(setNumberOfBackSeatPassengers:)];
then I get some junk number inserted for numberOfBackSeatPassengers cause I can’t explicitly pass-in a number as an argument when calling the method this way.
(Question: is there a way around this?)
2) aroth’s also absolutely right in saying that in Sportscar we can simply override the Car class’s setter and getter for numberOfBackSeatPassengers, and have these overriding methods reset it to 0, or give an error, etc. But while this is a very practical solution and seems to solve this particular problem, I feel like it doesn’t address the larger issue of @private not really seeming to do what it ought to do.
3) Redesigning the logic to have a class for FourDoorCar and another one for TwoDoorCar and then continue building off of that is an interesting option – but that almost feels like now Objective-C’s syntax is “forcing” itself on my programming logic and how I’m structuring my very project – and this feels like quite an imposition. Maybe I’m wrong and making too much out of this – but either way this all came about just because the @private isn’t doing what it seems to promise…? Doesn’t feel right.
At the end of the day I keep coming back to the same question: what good does @private actually do us? What benefits does it have, what does it “buy” me? It seems that if I want to have an iVar be private, I can just declare it in the “.m” file and not ever bother declaring it in the Header file in the first place. I mean am I right about this or not? or is there still some instance where you’d want to declare an iVar in the Header as @private, but not declare a setter and getter for it there in the Header – so those won’t be explicitly available to subclasses – and have it all make sense?
Can we think of an actual example for this? Is there some sort of Car property that I’d want to declare as @private in the Header (as opposed to in the “.m”) that would somehow benefit me?
I thought numberOfBackSeatPassengers would be a good example, but I’m not seeing how it’d really work in action, in actual code…
=========================================================================
EDIT #2 – Continuing the dialogue with @aroth ๐
@aroth – I absolutely agree that its much better/more organized to declare all iVars in the Header and not split things up so that some are in the Header and some are in the Implementation. That creates a mess and I really dislike that approach. (I noted in my original question that I don’t want to use the Implementation and/or Category approach to address my question.)
-Also, yes, properties absolutely don’t always have to be backed up by iVars.
-Regarding designing the Class appropriately, I concur that that of course is the key to good programming. The Car/Sportscar example is something I made up on the spot to give my question some context and I didn’t invest any time considering its design merits/flaws. I think if we were to take your approach however – which seems quite logical for sure – and go with a Car class, a FourDoorCar subclass, a TwoDoorCar subclass, etc. – we could solve a lot of problems – but its still very likely that sooner or later we’ll run into a situation where we’d perhaps want an @private iVar for one of our classes, and not want to create another subclass to deal with it.
I mean lets just assume that this would happen, for the sake of this discussion.
And so, if possible, I’d really like to think of a specific iVar for our Car class that it would make sense to have as @private, show in code how to use it, and discuss its scope and limitations.
I keep trying to think of a real-world example of some property of a Car that we would want only the Car to have – and that none of its subclasses should inherit.
I really thought numBackSeatPassengers would do the trick – and for the purposes of our discussion it still can, but, I’ll just make up another one and call it phantomIVar ๐
And so:
@interface Car : NSObject {
@private
//int numberOfBackSeatPassengers;
int phantomIVar;
}
@property (nonatomic, strong) NSString *make, *model;
@end
The Implementation would be:
@implementation Car
@synthesize make, model;
-(void) setPhantomIVar:(int)i {
phantomIVar = i;
}
-(int)phantomIVar {
return phantomIVar;
}
@end
Which pretty much puts us back where we started ๐
At least that’s how I feel.
I mean the only thing that the @private declaration seems to buy us is readability. So that now, anyone looking at the Header will be able to see that phantomIVar is an iVar of Car, and understand that its private. That’s it.
In terms of functionality however, it didn’t seem to do much. Cause its not like putting @private in front of phantomIVar freed us up to still be able write a setter/getter for it in the Header and have those be only accessible to Car class objects and not subclasses of Car. No, @private doesn’t get you that. To get privacy you’d have to go in the Implementation file and write your setter and getter there. And ultimately in Objective-C there’s no such thing as private methods. In Obj. C. they’re all public.
aroth, please let me know if I got this right – and if not, where exactly I went wrong.
Many thanks ๐
Not true. Those methods would still exist on every instance of
Carand every instance of every object that extendsCar, whether or not you declare them in your header file. The compiler wouldn’t treat them as publicly visible and would complain if you tried to call them directly, but you’d still be able to call your getter and setter on any subclass ofCarsimply by usingperformSelector:.In any case, if you have a
@propertythere’s no point is using@privateon the ivar that backs it (and there’s also no point in having an explicit ivar backing it, one will be created automatically for you when you use@synthesize; but that’s a separate topic). I’d suggest that ifSportsCaris meant to extendCarand never allow any backseat passengers to be recorded that the ‘standard’ way to do that would be to simply override the getter/setter methods inSportsCarto either always set/return 0 or to raise some error if an attempt is made to set a nonzero value.Another option, since this property does not apply to all
Carinstances is to take it out of the base class entirely. You could, for example, haveCar, and then derived from that haveTwoDoorCarandFourDoorCar, and then haveSportsCarbe derived fromTwoDoorCar. In this case you could declarenumberOfBackSeatPassengersas a public property ofFourDoorCar, as every four-door car should be able to accommodate passengers in the back seat.To get back to the original question being asked, using
@privateon an ivar affects only the visibility of that ivar. It does not affect methods which make use of the ivar. So a subclass ofCarwill not be able to see thenumberOfBackSeatPassengersivar itself. But since you’ve created a public getter/setter for it, the subclass will of course be able to see those, and use them to modify the value of the ivar.Edit
To briefly answer the updated question(s):
Yes, you can use NSInvocation to dynamically invoke a method that requires primitive parameters. Or you can use the approach discussed here, which is even more straightforward: Objective-C and use of SEL/IMP. Or you can use a
NSNumberinstead of anintand then useperformSelector:withObject:.I’m not sure what you’re saying
@privateshould be doing in this case. What is it that you think using@privateshould do?I think this has less to do with syntax and more to do with principles of object-oriented design. If some cars do not have a back seat, then it is not really good object-oriented design to give the
Carsuperclass anumberOfBackseatPassengersproperty. Doing that gives the object a field that does not actually apply to every instance of the object type. And when you start doing that you run into exactly the sort of problems you describe in your example. The purpose of a superclass is to contain functionality that is common to all of its derived types. If it has functionality that is common only to some of its derived types, then that is usually a design problem. In any case, it has nothing to do with Objective-C syntax or semantics.As for what
@privategets you, how about simplified organization of your class, for one thing? Yes you can declare an ivar in your implementation file to accomplish a similar effect, but is that really as convenient as having all the ivars declared in the header? On a reasonably complex project, will other developers be able to follow your code as easily if only some ivars are declared in the header and the rest are in the implementation file?Without
@private/@protectedevery ivar declared in a header would be public, which is definitely not good in an object-oriented environment for all the reasons Jonathan pointed out. So these access modifiers probably exist, first and foremost, to solve this issue.As for use-cases, properties with getters/setters are probably not the best example. The purpose of getters/setters is virtually always to provide a public interface for modifying/querying the property value, and as noted in Objective-C it’s not necessary to explicitly declare an ivar, in any scope, to back a synthesized property.
A better example may be
IBOutlet‘s. You want these declared in your header so that XCode/Interface Builder can find them, but you don’t want them exposed outside of your class implementation or (typically) even to subclasses of your class. So you would declare them in your header, and you generally would not add any getter/setter methods for these ivars.Edit 2
For a specific example of where
@privatemakes sense, what about something like:We know that proposed regulations may require all cars on the road to include a built-in black-box/data recorder. So every
Carmust have one, and no subclass ofCarshould be able to tamper withblackBoxRecorder.In this case having a setter method defined would not make sense. You might provide a public getter, or instead you might provide a public wrapper API around the
DataRecorderthat subclasses could use to log data. Something like-(void) logEventWithName:(NSString*)name andValue:(NSNumber*)value;. So subclasses can use theDataRecorderthrough the API, but they can’t mess with the backing ivar itself to disable or modify the behavior of the mandated black-box/data recorder.But in any case, yes, I’m in general agreement with your analysis. Having
@privatemostly impacts readability/maintainability of code. It needs to exist for Objective-C to be successful as an object-oriented programming language (if all ivars were public by default and there was no way to modify that, the language would be a complete mess), but what it does from a purely functional standpoint is not much. It’s more of a logical/organizational tool. It assists with data hiding and allows you to keep all of your ivars in your header file(s), and that’s about it.