NSString Release

不羁的心 提交于 2019-12-11 04:07:35

问题


I have this code of string and I have problems trying to free up memory, I have understood that only those who release it initializes and is not autorelease but I had problems with the string "end", and as nSum release.

NSString *urlBase = [[NSString alloc] initWithFormat:@"http://service.svc/"];
NSString *op = [[NSString alloc] initWithFormat:@"op1"];
NSString * final = [urlBase stringByAppendingFormat:op];
NSString * nSum = sumTextfield.text;
final = [final stringByAppendingFormat:nSum];

//release

[ urlBase release ];
[ op release ];
//[final release]; error
//[final autorelease]; error

thank for you help.

UPDATE:

- (IBAction)mostrarOpciones {
 // code (UP)
}

回答1:


If you create an object using a method that begins with init, new, copy, or mutableCopy, then you own that object and are responsible for releasing it (or autoreleasing it) when you're done with it. If you create an object using any other method, that object is autoreleased, and you don't need to release it. In that case, you actually need to retain the object if you want to keep it around. Apple has a Memory Management Programming Guide that includes all these rules.

The code you've posted is actually correct. You need to release urlBase and op because you created them using a method beginning with init (initWithFormat: in this case). final and nSum are already autoreleased for you. final was created by a method that doesn't begin with init, new, copy or mutableCopy (in this case, the factory method stringByAppendingFormat:). nSum was returned by a method called text, and you can assume that sumTextField "owns" it or has autoreleased it before returning it to you, and so you're not responsible for releasing it.




回答2:


you cannot release NSString which you did not allocate. Since your two variables are not allocated, they need not to be released.



来源:https://stackoverflow.com/questions/8702540/nsstring-release

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