目标 C - 分配、复制、保留 [英] Objective C - Assign, Copy, Retain

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

问题描述

我是 Objective C 的新手.我有 C 的基本知识,包括指针的概念.我有两个基本问题:

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

  1. 有人可以用一些类比来解释分配、复制和保留之间的区别吗?
  2. 如何处理返回指针变量的函数,以及如何通过返回指针执行消息传递?

推荐答案

已更改文档的更新答案

该信息现在分布在文档中的多个指南中.以下是必读的清单:

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

这个问题的答案现在完全取决于您是使用 ARC 管理的应用程序(新项目的现代默认设置)还是强制进行手动内存管理.

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 - 使用 assign 将属性的指针设置为对象的地址,而不保留它或以其他方式管理它;如果分配给它的对象被释放,则使用 weak 使属性自动指向 nil.在大多数情况下,您会希望使用 weak,这样您就不会尝试访问已释放的对象(非法访问内存地址 - EXC_BAD_ACCESS"),如果您不这样做不执行适当的清理.

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 - 声明的属性默认使用 retain(所以你可以完全省略它)并且会自动管理对象的引用计数,无论是否分配了另一个对象到属性或设置为零;使用 copy 自动向新分配的对象发送 -copy 消息(这将创建传递对象的副本并将该副本分配给属性 - 有用(甚至需要)在某些情况下,分配的对象在被设置为其他对象的属性后可能会被修改(这意味着修改/变异也适用于该属性).

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天全站免登陆