使用原始类型的属性 [英] Use of properties for primitive types

查看:63
本文介绍了使用原始类型的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解何时使用Objective C 2.0中的属性时遇到了麻烦.似乎您不需要基本类型的属性,例如:int,bool,float.这是真的?我看过一些示例,这些示例显示了这些类型的属性,而其他属性则省略了.例如,在Apple的示例代码中,它们具有:

I'm having trouble understanding when to use properties in Objective C 2.0. It seems you do not need a property for a primitive type such as: int, bool, float. Is this true? I have seen examples showing properties for these types and other leaving them out. For example, in Apple's sample code they have:

...
@interface Book : NSObject {
    // Primary key in the database.
    NSInteger primaryKey;
    // Attributes.
    NSString *title;
    NSDate *copyright;
    NSString *author;

    BOOL hydrated;
    BOOL dirty;
    NSData *data;
}

@property (assign, nonatomic, readonly) NSInteger primaryKey;
// The remaining attributes are copied rather than retained because they are value objects.
@property (copy, nonatomic) NSString *title;
@property (copy, nonatomic) NSDate *copyright;
@property (copy, nonatomic) NSString *author;
...

Apple SQLite图书清单示例代码

因此,您可以看到他们没有为BOOL使用属性,但是他们在整个实现文件中都将其视为具有实例变量,从而读取值并设置值. 在线搜索时,我发现了使用这些类型的属性的教程,例如:(@ property BOOL标志).有人可以帮我阐明一下这个话题吗?谢谢.

So as you can see they don't use a property for BOOL, but they treat it has an instance variable throughout the implementation file, reading the value and setting the value. Searching online I have found tutorials that do use properties for these types such as: (@property BOOL flag). Can someone shed some light on this topic for me? Thanks.

推荐答案

是的,您应该为基本类型声明一个属性.唯一真正的区别是您应该使用assign(这是默认设置,因此您也可以将其保留),而不是复制或保留.我无法代表本示例的其余部分,但是它可能是直接访问内部实例变量,或者是否正在从另一个类中进行访问,则键值编码正在生成访问器(这实际上是一种不好的形式).我猜是前者.如果我不需要特殊的访问器并且实例变量不在类之外使用,我将直接引用它而不是声明属性.有人可能会反对我的假设,但对我来说似乎有点过分.

Yes, you should declare a property for primitive types. The only real difference is you should use assign (which is the default, so you can also leave it out) instead of copy or retain. I can't speak for the rest of the example, but it's probably accessing the internal instance variable directly, or if it's being accessed from another class key value coding is generating an accessor (which is really bad form). I'm guessing it's the former; if I don't need a special accessor and the instance variable isn't used outside the class I'll just refer to it directly rather than declaring a property. Some people might argue against that I suppose, but it seems a little excessive to me.

这篇关于使用原始类型的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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