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

1 Answer 1

2

(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];
Sign up to request clarification or add additional context in comments.

6 Comments

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?
@golfromeo In that case, check if you might need to retain it.
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?
Certain methods return autoreleased objects and others don't. See the memory management guide for information on which methods do what. It's easy to tell by their name.
By the way, why use +stringWithString: instead of just assigning [folderNames objectatIndex:0] directly to gSdkPath?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.