Search code examples
iosnsstringcocos2d-iphoneplist

String from plist not standard string? Crash app using string from plist. iOS


Sorry for long post. String from plist crash my program when i using it in the second time. I have cocos2d project (attach) with one scene and one object. And one .plist file

HelloWorldLayer.h & .m (instantiate from CCLayer) 
NodeObject.h & .m (instantiate from CCNode)
Test.plist

In NodeObject i have one local string and two method

@interface NodeObject : CCNode
{
    NSString *stringForPrint;
}
-(void)createObjWithString:(NSString *)string;
-(void)printString;

In this both method we print string obtained in parameter string

-(void)createObjWithString:(NSString *)string
{
    stringForPrint = string;
    NSLog(@"NodeObject.createObjWithString stringForPrint >> %@", stringForPrint);
}

-(void)printString
{
    NSLog(@"NodeObject.printString stringForPrint >> %@", stringForPrint);
}

Plis content is one array with one dictionary whit item type string.

Root 
-TestArray <Array>
--item 0 <Dictionary>
---type <String> == "This is string from plist"

For test, into the scene i'm create NodeObject and get dada from plist. And print this string. It's work correctly.

if ([testDictionary objectForKey:@"TestArray"]) {
            for (NSDictionary *tempItemData in [testDictionary objectForKey:@"TestArray"]) {
                NSLog(@"type form plist in for loop > %@", [tempItemData objectForKey:@"type"]);//It's cool work. True string from plist.
            }
        }

I create my NodeObject into the loop. And it's work again.

if ([testDictionary objectForKey:@"TestArray"]) {
            for (NSDictionary *tempItemData in [testDictionary objectForKey:@"TestArray"]) {
                NodeObject *testObj = [NodeObject node];
                //and send it string from plist 
                [testObj createObjWithString:[tempItemData objectForKey:@"type"]];
            }
        }

BUT! if i have tried use this string in the printString method form NodeObject, app will crash without log. [testObj printString]; //crash app

I repeat. Object creation with manual string work. If using string from plist it's crash. I broke my head. And only in the second method. In the createObjWithStrig it work.

    //Work
    NodeObject *testObj = [NodeObject node];
    [testObj createObjWithString:@"manual string object"];
    [testObj printString]; // Print correct string

    //Crash
    NodeObject *testObj = [NodeObject node];
    [testObj createObjWithString:[tempItemData objectForKey:@"type"]];
    [testObj printString]; //Crash here

I'm attach project file. Can test this


Solution

  • On Apple forum i found the answer. Object i get out from plist is autoreleased. It's can not be just assigned and using later.

    I should use retain or copy.

    printString = [string retain];
    

    solved this problem.