Vikings
Vikings

Reputation: 2527

NSString Memory Leak Issues

I am creating global strings like this:

NSString *total = nil;

Is there another way to alloc memory to a string but set it to nil?

Upvotes: 0

Views: 185

Answers (2)

PrimaryChicken
PrimaryChicken

Reputation: 973

I guess if you allocate the global variables in one of the implement classes. I think you can release it in your AppDelegate function - (void)applicationWillTerminate:(UIApplication *)application {

first check whether it is allocated. And release it

if(total!=nil){ [total release]; }

Upvotes: 0

spegoraro
spegoraro

Reputation: 96

If you are wanting to create a global string then use the extern keyword outside of a class interface. So before your @interface declaration in your .h file, place something like

extern NSString *total;

Then in your .m file, before the @implementation declaration place something like

total = @"";

Otherwise if it's going inside a class somewhere then a simple:

NSString *total = [[NSString alloc] init];

should suffice.

I normally only use global strings as constants for NSNotifications, everything else can usually find a place in a singleton instance. Depending on what you're trying to achieve you may want to look into that in the Cocoa Programming Guide.

Upvotes: 1

Related Questions