1

我在我的应用程序中遇到了 NSString 的一些困难。基本上,我有一个名为 o1string 的 NSString,其中包含值“602”。我想在 UIAlertView 中将其与其他一些文本一起输出。

votedmessage = [ NSString stringWithFormat:@"The current standings are as follows:\n\n%@: %@ votes", b1title, o1string ];
UIAlertView *votedAlert = [[UIAlertView alloc] initWithTitle:@"Thank you for voting" message:votedmessage delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];

我使用了 NSLog 并验证了 NSString 中的值肯定是 602,并且消息中使用的另一个变量(b1title)可以自行输出。但是,当我将 o1votes 变量添加到警报消息中时,我无法弄清楚为什么应用程序会崩溃,这是否与在 NSString 中仅保存一个数字的冲突有关?

这就是 o1string 的设置方式。它肯定包含从 XML 文件中获取的“602”。

o1string = [[options objectAtIndex:3] objectForKey: @"votes"];
o1string = [o1string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
o1string = [o1string stringByReplacingOccurrencesOfString:@"    " withString:@""];
4

2 回答 2

6

Unless that assignment of o1string is in the same method where votedmessage is created (since you don't say, I'm assuming not), it will be gone by the time you get to the code where votedmessage needs it.

Unless you're using garbage collection, you need to retain objects that you want to keep around past the current method. See the Objective-C memory management guide for complete details.

于 2009-04-13T16:58:16.180 回答
0

You need to post more code. In particular it's not clear whether the two pieces you posted are in the same function or different places.

If they're in different places you must call [o1string retain] (and later [o1string release]). The easiest way to do this would be to make olstring a property with retain semantics.

stringByReplacingOccurrencesOfString returns a temporary instance that will be auto-released sometime after the function exists.

I would guess the reason b1Title works is that it's stored in your dictionary so is persistent. o1string is created from the stringByXXX functions and is temporary.

于 2009-04-13T17:00:34.600 回答