问题描述
一个101问题
假设我正在制作汽车数据库
,每个汽车对象定义为:
Let's say i'm making database of carsand each car object is defined as:
#import <UIKit/UIKit.h>
@interface Car:NSObject{
NSString *name;
}
@property(nonatomic, retain) NSString *name;
为什么 @property(nonatomic,retain)NSString * name;
而不是 @property(nonatomic,assign)NSString * name;
?
我明白了那个 assign
不会增加引用计数器,因为 retain
会这样做。但是为什么要使用 retain
,因为 name
是 todo $ c $的成员c>对象的范围是它自己。
I understand that assign
will not increment the reference counter as retain
will do. But why use retain
, since name
is a member of the todo
object the scope of it is to itself.
没有其他外部函数也会修改它。
No other external function will modify it either.
推荐答案
在Objective-C中没有对象的范围这样的东西。范围规则与对象的生命周期无关 - 保留计数就是一切。
There's no such thing as the "scope of an object" in Objective-C. Scope rules have nothing to do with an object's lifetime — the retain count is everything.
您通常需要声明实例变量的所有权。请参阅 Objective-C内存管理规则一>。使用保留
属性,您的属性设置器声明新值的所有权并放弃旧值的所有权。使用 assign
属性,周围的代码必须执行此操作,这在责任和关注点分离方面同样糟糕。您将使用 assign
属性的原因是您无法保留该值(例如非BOOL或NSRect等非对象类型)或保留它时引起不必要的副作用。
You usually need to claim ownership of your instance variables. See the Objective-C memory management rules. With a retain
property, your property setter claims ownership of the new value and relinquishes ownership of the old one. With an assign
property, the surrounding code has to do this, which is just as mess in terms of responsibilities and separation of concerns. The reason you would use an assign
property is in a case where you can't retain the value (such as non-object types like BOOL or NSRect) or when retaining it would cause unwanted side effects.
顺便说一下,在NSString的情况下,正确的属性通常是 copy
。这样,如果有人传入一个NSMutableString(它是有效的 - 它是一种NSString),它就无法从你的下方改变。
Incidentally, in the case of an NSString, the correct kind of property is usually copy
. That way it can't change out from under you if somebody passes in an NSMutableString (which is valid — it is a kind of NSString).
这篇关于Objective-C 101(保留vs赋值)NSString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!