Spero di avere qualche chiarimento su come Private vs Protected vs Public funziona rispetto ai membri della classe durante la programmazione in Objective-C - Pensavo di conoscere la differenza (ho aggiunto alcuni commenti alla mia classe genitore Person rispetto allo stesso), ma il fatto che il compilatore non si sia lamentato quando ho provato ad accedere ad un ivar/membro privato di una classe genitore tramite la sottoclasse ora mi ha confuso.Objective-C - Privato vs Protetto contro Pubblico
Qui è la mia classe genitore:
/*
Person.h
*/
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
//We can also define class members/iVars that are of type private
//This means they can only be accessed by the member functions
//of the class defining them and not subclasses
@private
int yob;
//We can also define class members/iVars that are of type public
//Public members can be accessed directly
@public
bool alive;
//By default class members/iVars are of type protected
//This means they can only be accessed by a class's own
//member functions and subclasses of the class and typically
//also by friend functions of the class and the subclass
//We can explicitly define members to be protected using the
//@protected keyword
@protected
int age;
float height;
}
@property int age;
@property float height;
@property int yob;
@property bool alive;
@end
Qui è la mia classe derivata Man:
/*
Man - Subclass of Person
*/
#import <Foundation/Foundation.h>
#import "Person.h"
@interface Man : Person
{
//iVar for Man
float mWeight;
}
@property float mWeight;
@end
E, infine, ecco la principale:
#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;
}
Il compilatore non dovrebbe lamentarsi del motivo per cui provo ad accedere a a.yob sopra? O usando @property & @synthesize (vale a dire i metodi setter e getter) ho essenzialmente reso quel membro protetto e quindi accessibile alla sottoclasse?
Nota a margine: se scrivi i tuoi ivar nel blocco @ implementation, anche @ public e @ protected non sono visibili dalla sottoclasse. Quindi la tua ipotesi è corretta solo per il blocco di interfaccia @. – Binarian