Object-Cで変数をプライベートにする方法がわかりません。Javaでは次のようにできます。
public class Counter {
private int cont;
public Counter(){
cont = 0;
}
public Counter(int v){
cont = v; }
public void setValue(int v){
cont = v;
}
public void inc(){
cont++; }
public int getValue(){
return cont;
}
}
その後:
public class MyClass extends Counter {
public static void main(String[] args) {
Counter myC = new Counter();
System.out.println(myC.getValue());
//System.out.println(myC.cont); don't work because it's private
}
}
明らかにプライベートであるため、変数myC.contにアクセスできません。Object-Cでは同じことを行いますが、機能しません。
@interface Counter : NSObject {
@private int count;
}
- (id)initWithCount:(int)value;
- (void)setCount:(int)value;
- (void)inc;
-(int)getValueCount;
@end
#import "Counter.h"
@implementation Counter
-(id)init {
count = 0;
return self;
}
-(id)initWithCount:(int)value {
self = [super init];
[self setCount:value];
return self;
}
- (void)setCount:(int)value {
count = value;
}
- (void)inc {
count++;
}
-(int)getValueCount {
return count;
}
@end
次に、main.mから呼び出します。
#import "Counter.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSLog(@"Hello, World!");
Counter *myC = [[Counter alloc] init];
[myC inc];
[myC inc];
[myC inc];
myC.count = 1;
NSLog(@"%d",myC.getValueCount); //it's 1 instead of 3
}
return 0;
}
count変数でアクセスできることを理解できません。Javaのようにプライベートにする方法はありますか?