gpt4 book ai didi

iphone - 具有相应ivars的属性概念

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:19:57 25 4
gpt4 key购买 nike

我有一个关于属性和 ivars 的一般性问题。

我见过许多使用属性的不同示例,这让我有点困惑。

方法 1 仅使用没有相应 ivar 的属性。

@property (...) Type *name;

@synthesize name;

方法 2 使用属性和 ivar

@interface{
Type *ivarName;
}
@property (...) Type *name;

@synthesize name = ivarName;

方法 3 忽略属性并使用 ivars

@interface{
Type *ivarName;
}
ivar = ...;

我目前对大多数事情都使用方法 1,它很管用。但我开始怀疑我是否可能在这里遗漏了一些东西。我已经阅读了很多关于 ivars VS 属性的问题,但似乎没有人真正关心它们如何协同工作。

在我见过的大多数示例项目中,都使用了方法 2。所以我的问题是:定义一个属性和一个 ivar,然后将属性分配给 ivar,是否比仅仅拥有一个属性有任何优势?

解决方案是否像这样简单:只有通过属性才能从“外部”设置 ivar?

我已阅读:Must every ivar be a property?Property vs. ivar in times of ARC但未能得出最终结论。

最佳答案

is the solution as simple as: only with a property can an ivar be set from 'outside'?

基本上,是的。 Obj-C 中的 Ivars(默认情况下)是“ protected ”,这意味着编译器不允许您在对象自身代码的外部访问它们。例如,给定以下类声明:

@interface Dunstable : NSObject
{
NSString * crunk;
}
@end

您可能认为您可以在创建对象后访问 ivar,但尝试会导致错误:

Dunstable * d = [[Dunstable alloc] init];
d->crunk = @"Forsooth"; // Error: "Instance variable 'crunk' is protected

这就是 ObjC 使用访问器方法的原因。在声明的属性出现之前,手动定义它们是强制性的:

@implementation Dunstable

- (NSString *)crunk {
return crunk; // implicit ivar access, i.e. self->crunk
}

- (void)setCrunk: (NSString *)newCrunk {
[newCrunk retain];
[crunk release];
crunk = newCrunk;
}

@end

现在,使用 @property@synthesize 指令为您创建那些访问器方法(以及变量本身)。 (setter 中的手动内存管理当然在 ARC 下也已过时。)

有可能制作一个可以从对象外部访问的ivar:

@interface Dunstable : NSObject
{
@public
NSNumber * nonce;
}
@end

Dunstable * d = [[Dunstable alloc] init];
d->nonce = [NSNumber numberWithInt:2]; // Works fine

但这不是好的 Objective-C 风格。

The Objective-C Programming Language文档包含关于此的“历史注释”:

Note: Historically, the interface required declarations of a class’s instance variables, the data structures that are part of each instance of the class. These were declared in braces after the @interface declaration and before method declarations: [...] Instance variables represent an implementation detail, and should typically not be accessed outside of the class itself. Moreover, you can declare them in the implementation block or synthesize them using declared properties. Typically you should not, therefore, declare instance variables in the public interface and so you should omit the braces.

这是一个相当大的变化(我真的很惊讶该文档中不再为 @interface 中声明的 ivar 提供语法),但它肯定是更好的。您应该使用声明的属性;他们做正确的事,让您的代码更干净、更安全。

关于iphone - 具有相应ivars的属性概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9854610/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com