Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

objective c - Use of properties for primitive types

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 Book List Sample Code

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...