+-
plist中的字符串不是标准字符串?使用plist中的字符串崩溃应用程序。 iOS版

很抱歉很长的帖子。当我第二次使用它时,plist中的字符串会崩溃我的程序。我有一个场景和一个对象的cocos2d项目(attach)。还有一个.plist文件

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

在NodeObject中,我有一个本地字符串和两个方法

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

在这两种方法中我们打印在参数字符串中获得的字符串

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

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

Plis内容是一个包含一个字典白名项类型字符串的数组。

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

为了测试,进入场景我创建节点对象并从plist获取数据。并打印此字符串。它工作正常。

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

我将NodeObject创建到循环中。它再次发挥作用。

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"]];
            }
        }

但!如果我尝试在printString方法窗体NodeObject中使用此字符串,则应用程序将在没有日志的情况下崩溃。 [testObj printString]; //崩溃应用

我重复。使用手动字符串工作创建对象。如果使用来自plist的字符串,它会崩溃。我弄坏了头。而且仅在第二种方法中。在createObjWithStrig中它可以工作。

    //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

我附上project file。可以测试一下

1
投票

您可以使用descriptionclass方法检查隐藏在变量背后的内容。

所以试试吧

NSLog(@"Description %@ and class %@",[[tempItemData objectForKey:@"type"]description],[[tempItemData objectForKey:@"type"]class]);

这可能会给你一些关于出错的地方的信息 - 也许它是空的)

0
投票

在Apple论坛上,我找到了答案。我从plist出来的对象是自动释放的。它不能只是分配和以后使用。

我应该使用保留或复制。

printString = [string retain];

解决了这个问题。