如何处理函数返回的对象以避免内存泄漏?
假设我有一个函数,
- (NSString *)fullNameCopy {
return [[NSString alloc] initWithFormat:@"%@ %@", self.firstName, self.LastName];
}
有人可以告诉我如何调用这个函数,如何将其值分配给新对象,以及如何释放它,避免内存泄漏和错误访问。
会像
NSSting *abc = [object fullNameCopy];
// 使用它并释放
[abc release];
还是我也应该分配 abc 字符串?
更新:
这里的要点是,我可以从函数返回非自动释放对象,然后在调用函数中释放它们吗?根据 Obj-C 函数命名约定,包含 alloc 或 copy 的函数名称应返回对象,假设调用函数具有所有权。
与上面的情况一样,我的函数“fullNameCopy”返回一个非自动释放的对象,我想在调用函数中释放它们。
Suppose I have a function
- (NSString *)fullNameCopy {
return [[NSString alloc] initWithFormat:@"%@ %@", self.firstName, self.LastName];
}
Can somebody tell me how to call this function, how to assign its value to a new object, and how then to release it, avoiding memory leaks, and bad access.
Would it be like
NSSting *abc = [object fullNameCopy];
// Use it and release
[abc release];
or I should alloc abc string too ?
Update:
The point here, Can I return non-autorelease objects from a function and then release them in the calling function. As per Obj-C function naming conventions, a function name containing alloc or copy should return object assuming that calling function has the ownership.
As in above case, my function "fullNameCopy" return a non-autoreleased abject, and I want to release them in the calling function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你是对的。由于方法名称包含单词“copy”,Cocoa 约定规定该方法返回一个由调用者拥有的对象。由于调用者拥有该对象,因此它负责释放它。例如:
或者,您可以使用
-autorelease
而不是-release
:You are right. Since the method name contains the word ‘copy’, Cocoa convention dictates that the method returns an object that is owned by the caller. Since the caller owns that object, it is responsible for releasing it. For example:
Alternatively, you could use
-autorelease
instead of-release
:请参阅此 更新后
:
Refer this post
UPDATE:
像这样:
然后
NSSting *abc = [object fullName];
Like This:
Then
NSSting *abc = [object fullName];
return [[[NSString alloc] initWithFormat:@"%@ %@", self.firstName, self.LastName]autorelease];
return [[[NSString alloc] initWithFormat:@"%@ %@", self.firstName, self.LastName]autorelease];