obj-c NSString和alloc / retain / release [英] obj-c NSString and alloc / retain / release

查看:126
本文介绍了obj-c NSString和alloc / retain / release的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个关于对象分配/保留/释放的更多问题,但我将以NSString为例。我知道我可以这样做:

This is probably a question that is more about object alloc/retain/release, but I'll use NSString as an example. I'm aware that I can do:

NSString* myString = [[NSString alloc] initWithString:@"Test"];

实质上是分配和初始化由变量myString引用的字符串,稍后应调用[myString release]在。但是,如果在执行此操作之后,将其设置为其他字符串,例如:

to essentially allocate and initialize a string referenced by my variable myString which I should later call [myString release] upon. However, if after I do this, I set it to some other string such as:

myString = someOtherString;

这样做确实会造成内存泄漏,因为我将指针重新分配给另一个对象并丢失了所有引用

does that essentially create a memory leak because I've reassigned my pointer to another object and lost all reference to the original one I allocated?

如果我只是想亲自分配并释放一个字符串,然后在不同时间更改其值,我是否应该使用其他语法?而不是'=',或者是重载以正确更改我使用=时最初由myString表示的对象的内容。

If I simply want to personally allocate and release a string and then change its value at various times, should I be using a different syntax other than '=' or is that overloaded to properly change the contents of the object that is originally represented by myString when I use =.

推荐答案

是的,在您的示例中,您正在泄漏内存。

Yes, in your example you are leaking the memory.

NSString* myString = [[NSString alloc] initWithString:@"Test"];
myString = someOtherString;

您应该这样做:

NSString* myString = [[NSString alloc] initWithString:@"Test"];
[myString release];
myString = someOtherString;

我所听到的描述整个保留/释放内容的最好方法是想象您正在walking狗某人。您的对象是一条狗,保留将一条皮带拴在狗上,而释放则将皮带拴住。您可以根据需要在狗身上绑很多皮带,但您想在狗身上至少绑上一条皮带,这样他就不会自由奔跑(泄漏),一旦您将它收回,就想将所有皮带从狗身上取走。给所有者(您想摆脱该对象)。在您的示例中,您可以将其视为放开狗的中途皮带并捡起另一只狗的皮带。

The best way I have heard the whole retain/release thing described is imagine you are walking a dog for someone. Your "object" is a dog and "retain" puts a leash on the dog and "release" takes a leash off. You can have as many leashes on the dog as you want but you want to keep at least one leash on the dog so he doesn't run free (leak) and you want to take all the leashes off the dog once you get it back to the owner (you want to get rid of the object). In your example, you can think of it as letting go of the leash on the dog mid-walk and picking up the leash of a different dog.

这篇关于obj-c NSString和alloc / retain / release的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆