0

对不起,长篇大论。当我第二次使用它时,来自 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"

为了测试,我在场景中创建NodeObject并从 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"]];
            }
        }

但!如果我尝试在 NodeObject 的 printString 方法中使用此字符串应用程序将崩溃而没有日志。[testObj 打印字符串]; //崩溃应用

我重复。使用手动字符串工作创建对象。如果使用 plist 中的字符串,则会崩溃。我摔断了头。并且仅在第二种方法中。在createObjWithSrig中它工作。

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

我附上项目文件。可以测试这个

4

2 回答 2

1

description您可以使用和class方法检查变量背后隐藏的内容。

所以试试

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

这可能会给你一些关于哪里出了问题的信息——也许它是空的)

于 2012-08-20T07:11:19.777 回答
0

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

我应该使用保留或复制。

printString = [string retain];

解决了这个问题。

于 2012-08-22T06:44:54.897 回答