我不明白如何在 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 中一样将其设为私有?