Storage of Objective C property variables and non property variables

扶醉桌前 提交于 2019-12-11 03:32:15

问题


Can anyone please clarify me that where exactly the variables stored in objective c ?

In .h file

@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

similarly,

In .m file

# 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

回答1:


"string", "textg", "number" and "numb" are instance variables to the class. The difference is that "string" and "number" are eligible to be publicly accessible (via ref->number), and "textg" and "numb" are private (since other classes conventionally do not #import .m files).

"mURL" and "sURL" properties are stored as instance variables "_mURL" and "_sURL". Again, "_mURL" is eligible to be publicly accessible (via ref->_mURL), and "_sURL" is not for the same reason.

And, "constant" is an ordinary global variable stored on the heap.




回答2:


You ask:

where exactly the variables stored

To answer just this: all the variables other than constant, and the variables used by the properties, are stored as part of the memory allocation for each instance of your class example that you create. Every instance has its own copy of each variable. E.g. when you do:

example *anExample = [example new];

You are requesting that an instance of example is created and a reference to it is stored in anExample. That instance contains the all the instance variables and properties you have declared (and it also contains any instance variables and properties for its superclasses, in this just just NSObject).

Your other variable, constant, is declared at the file level. Such variables are stored along with the compiled code in your file as part of your application. Regardless of how many instances of your class are created there is only ever one constant variable. Methods running on behalf of any instance all see the same constant variable.

HTH



来源:https://stackoverflow.com/questions/27773335/storage-of-objective-c-property-variables-and-non-property-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!