在PushScene之后,AppDelegate中保留的NSString丢失了

时间:2012-05-26 20:04:53

标签: iphone objective-c xcode nsstring cocos2d-iphone

在我的AppDelegate中,接近init方法的末尾,我调用[self setup]方法。此方法从URL获取字符串,修剪它,并将字符串分配给名为_songDirectory的属性。

以下是它在头文件中的显示方式:

@property (retain) NSString *_songDirectory;

以下是[setup]方法中的分配方式:

//set a URL string
NSString *urlString = [NSString stringWithFormat:@"http://www.blahblahblah.com/php/dev/blah.php?routine=blah"];

NSMutableString *infoString = [self getInfoStringFromURL: urlString];

//get the song directory as a string from the infostring
NSRange startIndex = [infoString rangeOfString:@"song_directory=="];
NSRange endIndex = [infoString rangeOfString:@"end_of_data=="];

_songDirectory = [NSString stringWithString: [infoString substringWithRange: NSMakeRange(startIndex.location + startIndex.length, endIndex.location - startIndex.location - startIndex.length)]];

NSLog(@"STRING IN APP DELEGATE: %@", _songDirectory);

NSLog在app delegate中调用时输出正确的字符串。但是,在我推送一个新场景后,我无法从中访问_songDirectory。推送场景中的以下代码产生EXC_BAD_ACCESS:

NSLog(@"STRING IN PUSHED SCENE: %@", [[[UIApplication sharedApplication] delegate] _songDirectory]);

我可以使用上面的语句来从app委托中获取内联但不是字符串。我很感激有些见解!

2 个答案:

答案 0 :(得分:2)

您将字符串直接分配给实例变量而不是属性,因此不保留字符串。它应该是self._songDirectory = ...而不是_songDirectory(您应该调用属性songDirectory,前导下划线通常仅用于私有实例变量)。

答案 1 :(得分:1)

您需要使用:

 self._songDirectory = [NSString stringWithString: [infoString substringWithRange: NSMakeRange(startIndex.location + startIndex.length, endIndex.location - startIndex.location - startIndex.length)]];

为了让财产得以发挥作用。否则你只是直接设置ivar并且保留不会发生。