Recently in the process of doing, suddenly found that the understanding of nsstring is still problematic. Therefore, I would like to add a blog, I hope to have just entered the OC development and do not know the memory leakage problem of the people a little guidance.
Assignment value:
NSString * str = @ "123"; The meaning of this code is actually attached to a constant to STR, which is automatically managed by the system, do not need release releases, will be autorelease.
NSString * str = [[Nstring alloc] Initwithstring: @ "111"]; This writing itself is problematic because the meaning of this code is to attach a constant to STR, so it is optimized by the compiler and therefore does not need to be release, despite the presence of Alloc.
NSString * str = [[NSString alloc] initwithformat:@ "123"];//Must be released to be able, because this will lead to memory leaks.
NSString * str = [[NSString stringwithformat:@ "111"];//does not require release, nor does it produce a memory leak, because that part calls the system's class method, which is autorelease. This method is also referred to as a temporary variable use method.
Add a little bit of content:
1, Initwithformat is an example method
Can only be called by nsstring* str = [[NSString alloc] initwithformat:@ "%@", @ "Hello World"], but must be manually released to free memory resources
2. stringWithFormat is a class method
Can be directly used nsstring* str = [NSString stringwithformat:@ "%@", @ "Hello World"] call, memory management is autorelease, without manual explicit release
Often in Uilable's fill-in, the use of strings, so it is very easy to cause memory leaks. Here are two ways to compare the correct methods:
There are two solutions:
1.
NSString * str = [[NSString alloc] initwithformat:@ "%@", @ "abc"];
Label.text = str;
[STR release]
Finally in Dealloc [label release]
2.
Label.text = [NSString stringwithformat:@ "%@", @ "abc"];
Also, for function calls, NSString is often used as a return value. So a more correct function is handled as follows:
A method that returns a NSString object that invokes the method in the event. and try the release method to return the NSString object.
[OBJC]View Plaincopy
- <span style="color: #454545" >-(nsstring*) createnewstring{
- //Case 1-</span><span style= "color: #ff0000" >-need to release </span><span style= "color: #454545" >.
- return [[[NSString alloc] initwithformat:@ "%@",@ "1223344"] autorelease];
- //Case 2-</span><span style= "color: #ff0000" >-system is automatically released. This method is not recommended because it is unsafe and has ambiguous meanings. </span><span style= "color: #454545" >
- return [[[NSString alloc] initwithstring:@ "1223344"] autorelease];
- //Case 3-</span><span style= "color: #ff0000" >-system is automatically released. </span><span style= "color: #454545" >
- return @ "1223344";
- }</span>
- Original http://blog.csdn.net/dongdongdongjl/article/details/8471995
iOS Common string NSString Auto-Release comprehension