that all pointer variables must be released when they're not used any more?
Only if the "pointer variable" points to an instance of an Objective-C class and only if you caused that instance to be retained previously. Read this: Memory Management Guide.
Every pointer variable ( *) is a class of some kind, or not?
If the pointer variable is declared as being a pointer to an instance of a class, then it will point to an instance of a class. Otherwise, it won't. Pointers are exactly that; a pointer -- a reference -- to a chunk of memory. That chunk of memory might be a class, an instance of a class, a C structure, or a raw buffer (or something else).
Every pointer variable therefore needs to be allocated and initialised using "alloc" and "init" (or similar)?
Only if the pointer points to an instance of an Objective-C class. If it is a C structure, you might use malloc()
. Even in the case of an Objective-C class, you might not alloc
anything:
NSString *foo = [NSString stringWithFormat: @"Hello, %@", @"World!"];
NSString *bar = @"bar";
NSBundle *main = [NSBundle mainBundle];
(BTW: None of the above need a -release
.)
When declaring variales using Object methods I may not need "alloc" or "init"?
This question indicates that you should go read -- and re-read (I read it about once every 18 months for the first decade I wrote Objective-C code, learning something each time) -- the Objective-C language guide.
You should probably also read something about the C language itself. That would likely help you to understand pointers vs. other types.
Number declarations (BOOL, int, float, etc) do not require memory management as long as they're not declared as a pointer?
Yes, but it is much simpler than being type specific. When you say int foo;
you are telling the compiler to carve out a bit of space in the local scope -- on the stack, generally -- to store an int's worth of data. When you say int *foo;
, you are telling the compiler to carve out a bit of space in the local scope to store a pointer to -- to store the address of -- a location in memory that contains an int.
Thus, NSArray *bar
is just a pointer to an instance and, yes, NSArray bar;
, if it were not explicitly disallowed, would carve out a chunk of space on the stack to hold an NSArray instance.
When you have a pointer to something that something must be initialized somehow and that is often done through allocation (but not always).