[ACCEPTED]-Objective-C - Private vs Protected vs Public-objective-c

Accepted answer
Score: 26

The usual trick is to create a class extension 7 inside the .m file and put your private/protected 6 property there instead of in the header.

//Person.m

@interface Person()

@property float height

@end

this 5 hides the 'height' property

Another trick 4 is if you want to create a readonly property 3 is to declare it in the header as

@property(readonly) int myproperty

but in 2 the class extension as readwrite which allows 1 your .m to modify the value using the getter/setter

@property(readwrite) int myproperty
Score: 17

visibility does not affect methods. methods 16 are as good as public when visible to clients 15 (and potential pitfalls/bugs when invisible 14 to clients). instead, visibility affects 13 instance variables. try this:

#import <Foundation/Foundation.h>
#import "Person.h"
#import "Man.h"


    int main (int argc, const char * argv[]) 
        {
            NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

            //Create a Person object
            Person * aPerson = [[Person alloc]init];

            //Create a Man object
            Man * aMan = [[Man alloc]init];


            //Let's attempt to modify our Person class members
            aPerson->height = 5.11; //Protected
            aPerson->age = 21; //Protected
            aPerson->yob = 2010; //Private
            aPerson->alive = YES; //Public


            //Let's now attempt to modify the same members via our
            //derived class Man - in theory, the private members should
            //not be accessible by the derived class man
            aMan->height = 6; //Protected
            aMan->age = 26; //Protected
            aMan->yob = 2011; //Private
            aMan->alive = YES; //Public
            aMan->mWeight = 190; //Protected member of Man Class



            [pool drain];
            return 0;
        }

this prevents 12 the subclasses from accessing ivars directly 11 -- forcing them and clients to use the accessors 10 (if provided).

this is all a bit weak because 9 categories allow clients to overcome this.

also, older 8 32 bit objc programs did't really check 7 that the visibility was declared correctly. fortunately, that's 6 been deprecated in 32 and an error in 64.

if 5 you really want something to be private 4 to subclasses and categories, use PIMPL 3 with an unpublished/opaque type.

method visibility 2 (as found in Java, C++, etc.) is a feature 1 i'd use in objc.

Score: 3

You are setting the visibilities of the 5 ivars, not the properties. Your properties 4 generate public getter and setter methods.

To 3 make private properties, you can put the 2 properties in a private category in the 1 .m file.

Score: 2

You aren't accessing the members - you are 2 accessing the property on Person which does not 1 have the access level specified.

More Related questions