本文介绍了@interface声明和@property声明之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C的新手,是目标C的新手.对于iPhone子类,我在@interface类定义中将变量声明为对类中的所有方法可见,例如

I'm new to C, new to objective C. For an iPhone subclass, Im declaring variables I want to be visible to all methods in a class into the @interface class definition eg

@interface myclass : UIImageView {
    int aVar;
}

然后我再次声明为

@property int aVar;

然后我

@synthesize aVar;

您能帮助我了解三个步骤的目的吗?我在做不必要的事情吗?

Can you help me understand the purpose of three steps? Am I doing something unnecessary?

谢谢.

推荐答案

在这里,您要声明一个名为aVar的实例变量:

Here, you're declaring an instance variable named aVar:

@interface myclass : UIImageView {
    int aVar;
}

您现在可以在班级中使用此变量:

You can now use this variable within your class:

aVar = 42;
NSLog(@"The Answer is %i.", aVar);

但是,实例变量在Objective-C中是私有的.如果您需要其他类来访问和/或更改aVar,该怎么办?由于方法是在Objective-C中公开的,因此答案是编写一个返回aVar的访问器(getter)方法和设置aVar的mutator(setter)方法:

However, instance variables are private in Objective-C. What if you need other classes to be able to access and/or change aVar? Since methods are public in Objective-C, the answer is to write an accessor (getter) method that returns aVar and a mutator (setter) method that sets aVar:

// In header (.h) file

- (int)aVar;
- (void)setAVar:(int)newAVar;

// In implementation (.m) file

- (int)aVar {
    return aVar;
}

- (void)setAVar:(int)newAVar {
    if (aVar != newAVar) {
        aVar = newAVar;
    }
}

现在其他类可以通过以下方式获取并设置aVar:

Now other classes can get and set aVar via:

[myclass aVar];
[myclass setAVar:24];

编写这些访问器和更改器方法可能非常繁琐,因此Apple在Objective-C 2.0中为我们简化了它.我们现在可以写:

Writing these accessor and mutator methods can get quite tedious, so in Objective-C 2.0, Apple simplified it for us. We can now write:

// In header (.h) file

@property (nonatomic, assign) int aVar;

// In implementation (.m) file

@synthesize aVar;

...,访问器/更改器方法将自动为我们生成.

...and the accessor/mutator methods will be automatically generated for us.

总结:

  • int aVar;声明一个实例变量aVar

@property (nonatomic, assign) int aVar;声明aVar

@synthesize aVar;实现aVar

这篇关于@interface声明和@property声明之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-11 04:13