我無法理解如何對象-C做出私有變量,在Java中我能做到這樣:如何做一個私有變量在對象-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訪問,因爲很明顯它是私有的,在對象的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;
}
我不明白,我可以在計數變量來訪問,我怎麼可以將其變爲私有象Java?
這是非常好回答另一個問題: [http://stackoverflow.com/questions/1262463/how-to-make-a-real-private-instance-variable][1] [1 ]:http://stackoverflow.com/questions/1262463/how-to-make-a-real-private-instance-variable – ahillman3
你讀過我的問題中的代碼?我已經做@私人,但不工作! – Piero
對不起。很高興我不是唯一那樣做的人。我會讓@sergio繼續。 – ahillman3