How to return correctly a NSMutableString from a method

妖精的绣舞 提交于 2019-12-11 11:56:36

问题


I'm looking for a good way to return a string constructed by a NSMutableString avoiding leaking :

eg:

+(NSString *)myMethod{



 NSMutableString *numberToReturn = [[NSMutableString alloc] init];
 [numberToReturn appendString:@"lorem ipsum"];


 return numberToReturn;
}

The leak instrument said I had leak with this variable.

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

thank you


回答1:


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;
}

or better yet for your example,

+ (NSString*)myMethod {
    NSMutableString *result = [NSMutableString stringWithString:@"lorem ipsum"];
    //...do something with result;
    return result;
}

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.




回答2:


You should autorelease the string before returning it. That's what the memory management rules say to do. If your app then crashes, that's evidence of a bug somewhere else in your code.



来源:https://stackoverflow.com/questions/1835629/how-to-return-correctly-a-nsmutablestring-from-a-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!