tags:

views:

3597

answers:

1

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.

+9  A: 

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.

Marc Charbonneau
Thanks Marc.Yeah, I was using properties for pretty much everything and was just scrubbing through my classes and making sure it was correct. I added the link to the Apple sample code I'm referring to in my question. But it does seem they are accessing it directly (not going through self.dirty)
Sean
Yes I agree don't need properties for primitives if there's no need. If you need to access it outside your class, then you need a property.
Mk12