开发者

NSString Returning?

how can i return NSString safely without any corruption of data? for example i have done like this..

-(NSString *)compose
{
  NSString *xml;
   return xml;
}
开发者_如何学运维

If xml has more than 2 kb, will it be returned safely...how can i allocate memory with autorelease every time?


The NSString class has been tested by Apple so it must not contain any corruption bug. Concerning the data size there is no limit excepted the memory. For the autorelease problem you have to add your object to the autorelease pool like that:

- (NSString *)compose {
    NSString *yourXMLText = [[[NSString alloc] initWithData:yourXMLData encoding:NSUTF8StringEncoding] autorelease];
    return yourXMLText;
}

For more information on the memory management you can see this: Memory Management Rules


The NSString method stringWithFormat: will return an autoreleased NSString, as will string and many others. In addition, you can call the autorelease method on an NSString to add it to the autorelease pool. I can't speak to size limits of NSStrings but I don't know of any reason they couldn't be that large offhand (I'm sure someone will correct me).


I would use one of the NSString convenience methods like David said.

NSString * xml = [NSString stringWithFormat:....];
return xml;

This will be autoreleased at the end of the run loop.


2Kb should not be a problem, but if you have this call in a tight loop (i.e. it's called lots of times without moving out of the method that called your compose method) there is a risk that you will consume memory that won't be released until later.

If you are worried about introducing memory leaks (I assume that's what you mean by corruption) then don't miss out on the amazingly useful instrumentation tool (easiest way is to go to the Run menu and pick Run with Performance Tools->Leaks. If the problem you were having was a dump and sudden exit you can check for Zombies (accessing released memory) from the Instruments tool directly:

File->New Select either iPhone or iPhone simulator (depending on what you want to run it on, I just use the simulator for most) and Memory option. Then pick Zombies from the right hand side Click Choose Set the default target (in the tool-bar) to Launch Executable->YourAppName

You will be able to identify the line of code causing the problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜