开发者

use NSString in other method?

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 retu开发者_如何学Gorn (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!


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];


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜