对象释放过程中出现的问题
我在何时以及要释放哪个对象期间遇到了一些问题
您可以说我对此的了解较少
我有以下条件请相应地建议我答案
- 情况1
NSMutableString *str=[[NSMutableString alloc]initWithFormat:@"Hello World! ”];
NSMutableArray *array=[[NSMutableArray alloc]init];
[数组addObject:str];
现在,当我尝试释放 str 时,将来数组的使用会受到影响......反之亦然
告诉我我可以同时释放两个吗?
- 情况2
NSMutableString *str=[[NSMutableString alloc]init]; str=@"你好世界!";
str=[自我获取数据]; //调用返回字符串的方法
[str释放];
我想我在这里造成了内存泄漏(如何解决?)
请清除这些情况
I have some problems during when and which object to be release
You can say my knowledge towards this is less
i have following conditions please suggest me the answer accordingly
- situation-1
NSMutableString *str=[[NSMutableString alloc]initWithFormat:@"Hello World!"];
NSMutableArray *array=[[NSMutableArray alloc]init];
[array addObject:str];
Now when i tried to release str then usage of array affected in future...and Vice Versa
Tell me can i release both?
- situation-2
NSMutableString *str=[[NSMutableString alloc]init];
str=@"Hello World !";
str=[self getData]; //calling a method which returns a string
[str release];
I think i am creating a memory leak here(how to solve it?)
please clear these situations
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在第一种情况下,您需要在将其添加到数组后调用
[str release];
,如下所示:这样,
array
保留了唯一的保留调用字符串。一旦稍后释放array
,就不会出现任何内存泄漏问题。对于第二种情况我有点困惑。
str
这里是一个指针。您似乎将三个不同的对象分配给同一个指针:当您调用
[str release]
时,您已经创建了内存泄漏,因为您丢失了第一个可变字符串。第二次调用str =
时,您失去了访问第一个NSMutableString
的任何方法。假设您希望连接所有这些(因为您选择了 NSMutableString),您可以尝试以下操作:
如果
[self getData]
方法返回一个自动释放的字符串,那就没问题了。如果getData
返回保留的字符串(如果您使用了alloc
和init
),则需要将其分配给中间指针并释放它将其添加到str
后。in the first situation, you'll need to call
[str release];
after adding it to the array, like this:This way,
array
holds the only retain call on the string. Once you releasearray
later, you won't have any memory leak issues.I'm a little confused about the second situation.
str
here is a pointer. You seem to be assigning three different objects to to same pointer:by the time you call
[str release]
, you've created a memory leak because you've lost the first mutable string. The second time you calledstr =
, you lost any way to access that firstNSMutableString
.Assuming that you're looking to concatenate all of these (since you chose NSMutableString), you might try this:
If the
[self getData]
method returns an autoreleased string, you'll be fine. IfgetData
returns a retained string (if you usedalloc
andinit
), you'll need to assign it to an intermediate pointer and release it after adding it tostr
.创建 NSMutableString 有何必要 您可以直接使用 NSString 来实现此目的
What is the need of creating the NSMutableString You can directly use NSString for this purpose