views:

403

answers:

4

It's really embarrassing but i stuck on it for two hours of trial and error.

I declared an NSString in the interface as:

NSString *testString;

Then i made a property and synthesized it. I allocate it in viewDidLoad with:

testString = [[NSString alloc] initWithFormat:@"thats my value: %i", row];

If i want to get the value of the string in another method it always return (null). So the string is empty, but why? how do i make it accessible for every function inside of one class? So i don't want to make a global var just a "global variable inside the class"

It's really confusing because as long as i code i never ran into this problem :(

thanks a lot for helping me!

+2  A: 

In your interface, declare the property:

@property (nonatomic, readwrite, retain) NSString *testString;

In the implementation, synthesize it:

@synthesize testString;

In the implementation, add a release to the -dealloc method:

[self.testString release];

In -viewDidLoad, access the property:

self.testString = [[[NSString alloc] initWithFormat:@"that's my value: %i", row] autorelease];
Alex Reynolds
A: 

I personally use

self.testString = [NSString stringWithFormat:@"my value: %i",row];

That way you don't need to worry about releasing it.

Also make sure you always use "self".

Chris Beeson
Thanks!ANd what is if i want to declare a nsstring inside viewcontroller1 and want to use it in viewcontroller to?I took the way with appDelegate.viewcontroller1.testString but that returns also (null) :(
Is your appDelegate or viewController null too?
Chris Beeson
how do i test this?
Just add a breakpoint at that point and hover your pointer over them
Chris Beeson
no everything here should be okay.(it shows all init'ed objects and so on...)
A: 

you can try to retain your string in viewDidLoad. but if it will work for you, don't forget to release it one more time

Morion
A: 

All other answers have you directly or indirectly retaining testString. However since you get testString with an alloc and an init, it is already owned by you without needing to be retained again.

I'm thinking your problem has to do with something else. You are either prematurely releasing testString in some method, or your viewDidLoad did not get called when you were trying to access your testString in other methods.

In order for you to use a variable defined in your implementation, you don't have to declare it a @property and @synthesize it. Those can help, but you don't have to have them. You may have to show us more code if this problem doesn't go away.

mahboudz