Official Forum for Programming in Objective-C (the iPhone Programming Language) - Stephen Kochan
September 20, 2018, 12:28:30 AM *
Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
 
   Home   Help Search Login Register Chat  
Pages: [1]   Go Down
  Print  
Author Topic: Violating private directives using categories  (Read 2097 times)
pierre
Newbie
*
Posts: 32


Email
« on: April 07, 2010, 02:43:48 PM »

Is it not the aim of the @private directive to restrict the scope of an instance variable to a class A? But, by adding a category, any class or module can access any private instance variable of A.

Example: The following class Foo has a private instance variable "secret".
Code: (Objective-C)
#import <Foundation/Foundation.h>
@interface Foo : NSObject {
NSInteger notSecret;
@private
NSInteger secret;
}
// Method declarations .
@end

@implementation Foo
// Method definitions
}
@end

The following category defined in any class or module adds the capacity to read or modify the private instance variable "secret" of Foo:

Code: (Objective-C)
#import "Foo.h"
@interface Foo (Treachery)
-(NSInteger) revealSecret;
-(void) changeSecret: (NSInteger) newSecret;
@end

@implementation Foo (Treachery)
-(NSInteger) revealSecret {
return secret;
}
-(void) changeSecret: (NSInteger) newSecret {
secret = newSecret;
}
@end

Is there a way to enforce privacy in Objective C, achieving a level of security similar to that of C++?
Logged
skochan
Administrator
Hero Member
*****
Posts: 3114



« Reply #1 on: April 07, 2010, 05:19:40 PM »

@private restricts access to subclasses. A category is not a subclass, rather an extension to an existing class, thus one could argue there is no violation here.

Cheers,

Steve
Logged
pierre
Newbie
*
Posts: 32


Email
« Reply #2 on: April 08, 2010, 08:20:10 AM »

The designer of the subclass can anyway access any of the superclass instance variable by defining a category extending that superclass. Formally maybe it is not a violation, but it is certainly a bypass.
Logged
skochan
Administrator
Hero Member
*****
Posts: 3114



« Reply #3 on: April 08, 2010, 11:40:34 AM »

Yeah, I guess you're right!

Cheers,

Steve
Logged
Pages: [1]   Go Up
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.11 | SMF © 2006-2009, Simple Machines LLC Valid XHTML 1.0! Valid CSS!
Entire forum contents ゥ 2009 classroomM.com. All rights reserved.