views:

76

answers:

1

In my Cocoa application, in the header file, I declare a NSString ivar:

NSString *gSdkPath;

Then, in awakeFromNib, I assign it to a value:

gSdkPath = @"hello";

Later, it's value is changed in the code:

gSdkPath = [NSString stringWithString:[folderNames objectAtIndex:0]];

(the object returned from objectAtIndex is an NSString)

However, after this point, in another method when I try to NSLog() (or do anything with) the gSdkPath variable, the app crashes. I'm sure this has something to do with memory management, but I'm beginning with Cocoa and not sure exactly how this all works.

Thanks for any help in advance.

EDIT: This was solved by retaining the string [gSdkPath retain].

+2  A: 

(the object returned from objectAtIndex is an NSString)

Are you sure? I suggest putting this in it's own temporary variable and double checking that it's not nil or invalid in some way.

Edit: If that is OK so far, do note that stringWithString returns an autoreleased object. You need to retain it if you want to use it "later".

gSdkPath = [NSString stringWithString:[folderNames objectAtIndex:0]];
[gSdkPath retain];
calmh
I checked by running the following code:NSString *testString = [folderNames objectAtIndex:0]; NSLog(testString);... It worked and correctly logged the variable, so I think it must be an NSString, right?
Chromium
@golfromeo In that case, check if you might need to retain it.
calmh
I added the retain, and it worked- how do I create strings that *aren't* autoreleased? And when I do that, when (if at all) should I release them?
Chromium
Certain methods return autoreleased objects and others don't. See the [memory management guide](http://developer.apple.com/mac/library/documentation/cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html) for information on which methods do what. It's easy to tell by their name.
calmh
Ok, thanks, really appreciate the help.
Chromium
By the way, why use +stringWithString: instead of just assigning [folderNames objectatIndex:0] directly to gSdkPath?
Preston
@Preston Maybe the string in question is prone to change, and you need a copy. Depends on the situation, of course.
calmh