1

I was on a roll learning objective-c, but I just don't get this. I'm declaring an nsstring i-var, i set the value in the init method, and then when I access that ivar in a later instance method, it crashes or behaves unpredictably.

//heres what my declaration looks like
@interface StockData : CCNode {
NSString *myPath;
NSString *myPath2;
}

-(id) init
    {
    if ( (self = [super init]) ){
        myPath = [[NSBundle mainBundle] pathForResource:@"stocks" ofType:@"sqlite"];
        myPath2 = @"test";
        CCLOG(@"mypath::::%@",[myPath class]);
        CCLOG(@"mypath2::::%@",[myPath2 class]);
}
    return self;
}
-(void) getChunk{
    CCLOG(@"mypath_getchunk::::%@",[myPath class]);//this crashes
    CCLOG(@"mypath2_getchunk::::%@", [myPath2 class]);//this doesn't
....

i am using cocos2d, and I am calling getChunk method in an scheduled update method like this:

-(void) updateOncePerSecond:(ccTime)delta{
if(!sd){
    sd = [StockData initStockData];
    [self addChild:sd]; 
}
[sd getChunk];
NSLog([sd getDate]);
}

the first time it iterates through I get this:

2012-03-19 20:33:58.591 HelloWorld[6777:10a03] mypath_getchunk::::__NSCFString
2012-03-19 20:33:58.591 HelloWorld[6777:10a03] mypath2_getchunk::::__NSCFConstantString

the second time it iterates through(if it doesn't crash):

2012-03-19 20:33:59.589 HelloWorld[6777:10a03] mypath_getchunk::::NSMallocBlock
2012-03-19 20:33:59.589 HelloWorld[6777:10a03] mypath2_getchunk::::__NSCFConstantString

why does it crash sometimes, and not other times. Why is it turning into a mallocblock? Are NSString's buggy, or am I doing it wrong. other variables seem to be working fine? How can I get my NSCFString to behave like that NSCFConstantString. I like that one better cause it doesn't crash. Any advice would be much appreciated!!! thanks!

1
  • What memory management are you using ARC, garbage collection or retain/release? Commented Mar 19, 2012 at 12:51

1 Answer 1

4

The string pathForResource:ofType: is autoreleased, which means it will be released “sometime later”. If you want to keep it alive, retain it:

myPath = [[[NSBundle mainBundle] pathForResource:@"stocks" ofType:@"sqlite"] retain];

And don't forget to release it later in dealloc.

Sign up to request clarification or add additional context in comments.

Comments

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.