目标C - 转让,复制,保留 [英] Objective C - Assign, Copy, Retain

查看:119
本文介绍了目标C - 转让,复制,保留的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我新的目标C.我必须用C的基本知识,包括指针的概念。我有两个基本问题:


  1. 可以有人解释分配,副本之间的差异,并与一些比喻挽留?

  2. 你是如何处理它返回指针变量的函数,你如何执行通过返回指针通讯?


解决方案

有关更改文档的更新答案

该信息现在正穿过文档中的一些指南$ P $垫。这里是必读的列表:

在回答这个问题现在完全取决于您是否正在使用ARC管理应用(现代默认为新项目)或强制手动内存管理。

分配与弱 - 使用指定设置属性的指向对象的地址,而不保留或以其他方式策它;使用有属性点零如果自动分配给它的对象被释放。在大多数情况下,你要使用这样你就不会试图访问一个释放的对象(内存地址的非法访问 - EXC_BAD_ACCESS ),如果你不进行适当的清理。

保留与复制 - 声明的属性使用保存按默认值(这样你就可以简单地完全忽略它),并自动管理对象的引用计数是否有另一个对象分配的财产,或者它设置成零;使用复制以自动发送新分配对象的 -copy 消息(这将创造传递的对象的副本,该副本分配给属性来代替 - 在某些情况下分配的对象可能被设置为某些其他对象的属性后进行修改很有用(甚至要求)(这将意味着修改/突变将适用于财产所有权以及)

I'm new to Objective C. I have basic knowledge in C, including the concept of pointers. I have two basic questions:

  1. Can someone explain the difference between assign,copy, and retain with some analogy?
  2. How do you handle a function which returns pointer variable, and how do you perform messaging through a return pointer?

解决方案

Updated Answer for Changed Documentation

The information is now spread across several guides in the documentation. Here's a list of required reading:

The answer to this question now depends entirely on whether you're using an ARC-managed application (the modern default for new projects) or forcing manual memory management.

Assign vs. Weak - Use assign to set a property's pointer to the address of the object without retaining it or otherwise curating it; use weak to have the property point to nil automatically if the object assigned to it is deallocated. In most cases you'll want to use weak so you're not trying to access a deallocated object (illegal access of a memory address - "EXC_BAD_ACCESS") if you don't perform proper cleanup.

Retain vs. Copy - Declared properties use retain by default (so you can simply omit it altogether) and will manage the object's reference count automatically whether another object is assigned to the property or it's set to nil; Use copy to automatically send the newly-assigned object a -copy message (which will create a copy of the passed object and assign that copy to the property instead - useful (even required) in some situations where the assigned object might be modified after being set as a property of some other object (which would mean that modification/mutation would apply to the property as well).

这篇关于目标C - 转让,复制,保留的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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