如何从方法正确返回NSMutableString [英] How to return correctly a NSMutableString from a method
问题描述
我正在寻找一种返回NSMutableString构造的字符串以避免泄漏的好方法:
I'm looking for a good way to return a string constructed by a NSMutableString avoiding leaking :
例如:
+(NSString *)myMethod{
NSMutableString *numberToReturn = [[NSMutableString alloc] init];
[numberToReturn appendString:@"lorem ipsum"];
return numberToReturn;
}
泄漏仪器说我有这个变量泄漏.
The leak instrument said I had leak with this variable.
我尝试了自动发布,但是崩溃了 我试图返回一个副本或将可变字符串复制到nsstring中,但仍然存在泄漏.
I tried autorelease but it crashes I tried to return a copy or copying the mutablestring into a nsstring but leak still present.
有什么主意或把戏吗? 每次用户在文本字段中键入一个值时,我都有一个调用此方法的应用程序,因此由于内存管理不当而导致应用程序崩溃...
Any idea or trick? I'have a to call this method each time the user type a value into the textfield, so the application crashes due to bad memory management...
谢谢
推荐答案
您应使用-autorelease
.您的方法应写为:
You should use -autorelease
. Your method should be written as:
+ (NSString*)myMethod {
NSMutableString *stringToReturn = [[NSMutableString alloc] init];
[stringToReturn appendString:@"lorem ipsum"];
return [stringToReturn autorelease];
}
如果发生崩溃,则故障在其他地方.
If there is a crash, the fault is elsewhere.
当然,您可以利用工厂方法来返回已经自动释放的实例,并将方法改写为
Of course, you can make use of factory methods that return an already-autoreleased instance, rewritting your method as
+ (NSString*)myMethod {
NSMutableString *result = [NSMutableString string];
[result appendString:@"lorem ipsum"];
return result;
}
或者更好的例子,
+ (NSString*)myMethod {
NSMutableString *result = [NSMutableString stringWithString:@"lorem ipsum"];
//...do something with result;
return result;
}
很明显,如果您的方法的唯一目的只是返回带有字符串的新字符串,则可以避免整个方法,如果确实需要可变的字符串,请使用[NSMutableString stringWithString:@"lorem ipsum"]
.
Obviously if you method's only purpose is just to return a new string with a string, you can avoid the whole method all together and use [NSMutableString stringWithString:@"lorem ipsum"]
if you really need a mutable string.
这篇关于如何从方法正确返回NSMutableString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!