2012-10-24 26 views
-1

我無法理解如何對象-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?

+1

這是非常好回答另一個問題: [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

+0

你讀過我的問題中的代碼?我已經做@私人,但不工作! – Piero

+0

對不起。很高興我不是唯一那樣做的人。我會讓@sergio繼續。 – ahillman3

回答

1

myC.count不在訪問你的變量,它訪問你定義的方法-(int)count;。由於myC是Counter類型的指針,因此您可以通過取消引用指針來直接訪問其成員變量,如myC->count。然而這並不可取。 Obj-C內置了用@property關鍵字生成getter和setter的功能。

但在`-(int)count的一個斷點,並觀察該方法被調用。

+0

你有權利,現在我編輯了我的問題和代碼,但無論如何工作,所以問題是不固定的... – Piero

+0

我已經清理項目,現在工程.. 。 – Piero

0

,最好的辦法是使用一類延伸,並在.m文件中定義的私有變量:

MyClass.h

@interface MyClass 
    <PUBLIC DECLARATIONS, variables and methods> 
@end 

MyClass.m

@interface MyClass() 
@property (nonatomic,...) int count; 
... 
- (void)privateMethod:(...; 
@end 

@implementation MyClass 
@synthesize count; 
... 
- (void)privateMethod:(...) { 

} 
... 
@end 
+0

你有沒有讀過我的問題中的代碼?我已經做@私人,但不工作! – Piero

+0

好的,請看看我的編輯... – sergio

+0

好的,我已經知道這樣做的方式,但我的問題是爲什麼不用@private? :) – Piero