views:

54

answers:

4

i have this code

#import <Foundation/Foundation.h>
int testint;
NSString *teststring;

int Test()
{
    NSLog(@"%d",testint);
    NSLog(@"%@",teststring);
}


int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    testint = 5;
    NSString *teststring = [[NSString alloc] initWithString:@"test string"];
    Test();
    [pool drain];
    return 0;
}

in output i have:

5 (null)

why Test function doesn't see correct teststring value? What should I do, to have correct "test string" in output?

+1  A: 

You have two different variables named testint. The one in main() is shadowing the global one.

Ahruman
+5  A: 

You're shadowing a global variable with a local one. If the intent is to use the global testString, you shouldn't re-declare it with "NSString*".

Dan Olson
how should i declare global objects with "alloc init"?
cru3l
Probably inside a dedicated initialize function, or main. Just take the type off and it becomes an assignment instead of a declaration. You could also consider not using global variables and passing the data in to the functions that need them.
Dan Olson
+2  A: 

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).

Peter Hosey
A: 

how should i declare global objects with "alloc init"?

Strings are a special case. You can do this:

NSString* foo = @"bar";
JeremyP