如何在Object-C(如Java)中使变量私有
我不明白如何在Object-C中使变量私有,在Java中我可以这样做:如何在Object-C(如Java)中使变量私有,java,objective-c,Java,Objective C,我不明白如何在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
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
然后从主界面调用它。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中那样私有?最好的方法是使用类扩展并在
.m
文件中定义私有变量:
MyClass.h
@interface MyClass
<PUBLIC DECLARATIONS, variables and methods>
@end
myC.count
不是访问变量,而是访问您定义的方法-(int)count代码>。因为myC是一个计数器类型的指针,所以您可以通过像somyC->count
那样取消对指针的引用来直接访问其成员变量。然而,这是不可取的。Obj-C内置了使用@property关键字生成getter和setter的功能
但是,`-(int)count
中有一个断点,并观察该方法被调用。这在另一个问题中得到了很好的回答:[[1]:你读过我问题中的代码了吗?我已经读过@private但不起作用了!对不起。很高兴我不是唯一一个这样做的人。我会让@sergio继续。你读过其他答案了吗?myC.count
不是变量访问,它正在发送消息。你读过我问题中的代码了吗?我已经读过@private但不起作用了!好的,我已经知道了w这样做,但我的问题是为什么不使用@private?:)你甚至没有收到警告吗?以前版本的GCC只会发出警告…你可能也禁用了警告…不,我没有任何警告,我已经创建了一个新项目,所以我不认为警告被禁用了…我已经尝试过你的解决方案在上,但我可以从另一个类访问count变量…你是对的,现在我已经编辑了我的问题和代码,但仍然有效,所以问题没有解决…我已经清理了项目,现在可以工作了。。。
@interface MyClass ()
@property (nonatomic,...) int count;
...
- (void)privateMethod:(...;
@end
@implementation MyClass
@synthesize count;
...
- (void)privateMethod:(...) {
}
...
@end