在@interface声明一个ivar和在@implementation中放置变量之间的区别 [英] Difference between declaring an ivar in @interface and putting variable in @implementation

查看:172
本文介绍了在@interface声明一个ivar和在@implementation中放置变量之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@interface 中声明一个ivar与在 @implementation 中放置一个变量之间的区别是什么a .m文件?

What is the difference between declaring an ivar within an @interface versus putting a variable within an @implementation in a .m file?

@interface MyClass : NSObject {
  int num;
}
- (void)doSomething;
@end

vs。

@implementation MyClass   
int num2;

- (void)doSomething {
  num = 137;
  num2 = 138;
}
@end

是否有时间 @implementation

推荐答案

ivar并在实现中声明一个变量是实现中的变量在文件范围和全局变量。这意味着所有实例(和任何静态方法)将共享同一个变量;即如果你的对象的一个​​实例改变了变量,它会为所有实例改变它。

The difference between using an ivar and declaring a variable inside the implementation is that the variable within the implementation is at file scope and global. That means all instances (and any static methods) will share the same variable; i.e. if one instance of your object changes the variable, it will change it for all instances.

在文件范围定义它的用例是存储静态方法(直接作用于类而不是类的实例的方法)。一个真正常见的用例是Singleton的设计模式。您可以在此文件中定义类的静态实例,以便随时确保您正在访问同一个实例。您可以提供一个返回此实例的静态方法,以便代码中的任何对象都可以通过直接在您的类上调用该方法访问同一对象。

The use case for defining it at file scope is to store things for static methods (methods that act directly on the class instead of an instance of the class). A really common use case for this is the Singleton design pattern. You can define a static instance of your class within this file so that at any time, you can ensure you are accessing the same instance. You can provide a static method that returns this instance so any object in your code can access that same object by calling the method directly on your class.

更新4 / 17/14

现在的常见做法是使用属性。这将创建getters和setter,让你自动使类更具可扩展性(如果你决定改变一个属性的工作方式,也许你想改变它总是被动态计算,类的公共接口不需要改变)。

Common practice now is to use Properties. This creates getters and setters for you automatically making the class more extensible (if you decide to change the way a property works, perhaps you want to change it to always be calculated on the fly, the public interface of the class does not need to change).

您可以使用私有类扩展来声明私有属性和方法。这具有保护某些属性和方法不被外部类访问的效果。

You can use private class extensions to declare "private" properties and methods. This has the effect of protecting certain properties and methods from being accessed by outside classes.

这篇关于在@interface声明一个ivar和在@implementation中放置变量之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆