questions about objective-c class methods
I know that class variables are declared in memory (as opposed to on the stack) when the class is initialized, and I know how class methods are basically used. But I have some questions about class methods that ar开发者_开发百科en't answered in the basic documentation.
Are class method also declared in memory? What about any object declared within these class methods? Are they 'static' in scope? What about any objects that are passed into a class method as parameter? Are those also 'static'?
Does repeatedly calling a class method mean all the objects declared within it are allocated again and again (one per method call), or are they living in one location in memory? Do they get cleared at every run?
For example, what happens to the do_something method here:
+ (void) main
{
while (i < MAX)
{
[MyClass do_something];
}
}
+ (void) do_something
{
NSMutableArray *array = [[NSMutableArray alloc] init];
...
[array release];
}
Class methods follow the same rules as object (instance) methods except you cannot access instance variables from class methods, obviously because ivars get allocated per object instance.
In your example "array" is allocated on heap with each call, as usual.
All variables are stored "in memory", no matter their storage type (static, automatic, free store), location (stack or heap), linkage or scope. A variable is static only if it's declared static. Otherwise, variables in class methods, whether parameters or local variables, have function or local scope, automatic storage, no linkage and are stored on the stack.
Class methods have global scope and external linkage, though you can send a message to an object (including classes) even if there isn't a handler in scope. Internal linkage should be possible, but I don't think the language supports declaring methods with internal linkage. Storage type and location doesn't really apply to methods, but you could say methods have static storage.
When calling the +(void) do_something
method the array
object will be initialised, as your code specifies, every time. It is only declared the scope of that method.
You can declare static variables in the class scope. These, as you'd expect, are accessible to all instances and class (aka static) methods.
See: http://www.otierney.net/objective-c.html#class
精彩评论