Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private properties and methods in Objective-C

In looking at one of Apple's examples, in the TableViewController.m, they have this:

// Private TableViewController properties and methods.
@interface TableViewController ()

@property (nonatomic, retain) NSMutableArray* sectionInfoArray;
@property (nonatomic, retain) NSIndexPath* pinchedIndexPath;
@property (nonatomic, assign) NSInteger openSectionIndex;
@property (nonatomic, assign) CGFloat initialPinchHeight;
... more properties and methods
@end

@implementation TableViewController
... usual stuff

I'm wondering why they put these properties in the .m file and how this is private. It seems like anyone who imports the TableViewController.m file can use these properties and methods right? Why not use the @private in the .h file?

like image 375
Crystal Avatar asked Jul 21 '11 15:07

Crystal


1 Answers

What they're doing is declaring a category on the class, but since this is done in the .m file, the effect is that those methods are "invisible".

This doesn't mean however that those methods cannot be called from the outside. This is due to the fact that there is no real privacy in objective c, because we're dealing with messages, not method calls. This means you can send an object a message even if you do not know if that object actually implements the method you're trying to call. The receiving object will determine at runtime if it can handle this call, maybe it will even forward it, and it will make no difference whether the method was known to the calling object or not.

This is one of the reasons why it is possible to call private APIs and get rejected for it.

like image 55
Toastor Avatar answered Oct 06 '22 01:10

Toastor