存储Objective C属性变量和非属性变量

时间:2015-01-05 04:15:03

标签: objective-c variables object properties storage

任何人都可以向我澄清一下,变量存储在目标c中的确切位置吗?

在.h文件中

@interface example: NSObject
{
  NString *string;      // where is this stored
  int     number;       // where is this stored
}
@property (nonatomic,strong) NSURL* mURL;  // where is this stored

@end

类似地,

在.m文件中

# import "xyz.h"

NSString *constant = @"hello";  // where is this stored

@interface example()
{
  NString *textg;      // where is this stored
  int     numb;       // where is this stored
}
@property (nonatomic,strong) NSURL* sURL;  // where is this stored

@end

2 个答案:

答案 0 :(得分:2)

" string"," textg"," number"并且"麻木"是类的实例变量。区别在于"字符串"和"数字"有资格公开访问(通过ref->号码)," textg"并且"麻木"是私有的(因为其他类通常不会#import .m文件)。

" mURL"和" sURL"属性存储为实例变量" _mURL"和" _sURL"。再次," _mURL"有资格公开访问(通过ref-> _mURL)和" _sURL"不是出于同样的原因。

而且,"常数"是存储在堆上的普通全局变量。

答案 1 :(得分:1)

你问:

  

存储变量的确切位置

回答这个问题:除constant以外的所有变量以及属性使用的变量都存储为您创建的类example的每个实例的内存分配的一部分。每个实例都有自己的每个变量的副本。例如。当你这样做时:

example *anExample = [example new];

您正在请求创建example的实例,并且对anExample的引用存储在NSObject中。该实例包含您声明的所有实例变量和属性(它还包含其超类的任何实例变量和属性,仅此constant)。

您的其他变量constant在文件级别声明。这些变量与编译后的代码一起存储在您的文件中,作为应用程序的一部分。无论创建了多少个类的实例,都只有一个constant变量。代表任何实例运行的方法都看到相同的{{1}}变量。

HTH

相关问题