【问题标题】:Retained NSString in AppDelegate lost after a PushScene在 PushScene 后 AppDelegate 中保留的 NSString 丢失
【发布时间】:2012-05-27 04:11:41
【问题描述】:

在我的 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 在应用程序委托中调用时打印正确的字符串。但是,在我推送新场景后,我无法从中访问 _songDirectory。推送场景中的以下代码产生 EXC_BAD_ACCESS:

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

我可以使用上面的语句从应用程序委托中获取整数,而不是字符串。我将不胜感激!

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      你需要使用:

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

      为了让属性正常工作。否则你只是直接设置 ivar 而不会发生保留。

      【讨论】:

      • 成功了!我会支持你,但我没有足够的声誉。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-19
      • 2015-06-16
      相关资源
      最近更新 更多