in output i have:
5 (null)
why Test function doesn't see correct teststring value?
Because you never assigned anything there. In main
, you declared a local variable with the same name, and initialized that variable with the pointer to the NSString object you created.
how should i declare global objects with "alloc init"?
You don't.
Declarations create variables (or sometimes types). The NSString *teststring
lines (both of them) are declarations: One of a global variable, the other of a local variable.
alloc
messages (and most other messages to classes) create objects.
Thus, this line:
NSString *teststring = [[NSString alloc] initWithString:@"test string"];
declared a local variable (teststring
) and created a string object, and initialized the variable to hold the pointer to the string object.
(Note that “initWithString:
” initializes the object, not the variable. The part from the =
until the semicolon is the initializer for the variable.)
You meant to assign to the global variable, not declare a local variable. So, do that: Leave out the type specifier to turn the declaration into an assignment statement:
teststring = [[NSString alloc] initWithString:@"test string"];
By the way, you don't need to use alloc
and initWithString:
here. @"test string"
is already an NSString object. And when you do alloc
something, don't forget to release it (assuming you didn't turn on the GC).