加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Objective-C – 编写简单方法的最佳实践?

发布时间:2020-12-16 10:28:12 所属栏目:百科 来源:网络整理
导读:在以下功能中哪一个是最佳实践? 要发送自动释放的对象,并让调用者保留它? 或发送一个已分配的对象,并让调用者释放它? - (NSString*) convertDataToString :(NSData*)myData{ //just an example,method might not exist NSString *str = [[NSString alloc]
在以下功能中哪一个是最佳实践?

>要发送自动释放的对象,并让调用者保留它?
>或发送一个已分配的对象,并让调用者释放它?

- (NSString*) convertDataToString :(NSData*)myData
{
     //just an example,method might not exist
     NSString *str = [[NSString alloc] initWithData:myData];
     return str;
     return [str autoRelease];
}

解决方法

memory management rules说你的第一个例子是 – 这是直接引用 – 错误.这甚至不是偏好问题,因为这里的一些答案似乎表明了这一点.调用者通常不拥有您返回的对象,因此应该自动释放.

规则中的具体示例说明了这一点:

This is wrong. Following the ownership policy,it would result in a memory leak.

– (NSArray *)sprockets {

    NSArray *array = [[NSArray alloc] initWithObjects:mainSprocket,auxiliarySprocket,nil];
    return array;
}

The object’s reference to the new array object is limited to the sprockets method. After the method returns,the object loses its reference to the new object so cannot relinquish ownership. That in itself is not a problem. However,following the naming convention set out earlier,the caller is given no indication that it owns the returned object. The caller would therefore not relinquish ownership of the returned object,leading to a memory leak.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读