IIS7 Rewrite
IIS7 Rewrite

Reputation: 799

Confusing Objective-C class structure

Here's a (reduced) class declaration from an example on apple's developer:

@interface myController : UITableViewController {

    NSArray *samples;
}

@property (nonatomic, retain) NSArray *samples

What is the purpose of declaring

{

    NSArray *samples;
}

when you declare it again as a property? If you leave out:

{

    NSArray *samples;
}

you can still use @synthesize in your .m and get a reference to it!

I'm a little confused as to the purpose of the first declaration.

Thanks

Upvotes: 0

Views: 450

Answers (2)

Jon Reid
Jon Reid

Reputation: 20980

With a property declaration, there is no purpose or benefit in explicitly declaring the backing instance variable. It's just leftovers from habit.

Edit: For iOS or Mac 64-bit Intel, explicitly declaring ivars was never needed for properties. But they were needed for other Mac work — hence the examples.

Also, I did find a difference. When an ivar is explicitly declared, unless you state otherwise, it is a protected ivar, available to subclasses. But when an ivar is implicitly created for a property, subclasses don't have access to the ivar.

Upvotes: 1

Max
Max

Reputation: 16719

Properties are just a handy way to declare accessors to you data. It usually leads to some member variable but not necessarily. And that member var can have different name:

@interface myController : UITableViewController {

    NSArray *mSamples;
}

@property (nonatomic, retain) NSArray *samples
@end

@implementation
@synthesize samples = mSamples;
@end

Or you can use properties without vars at all:

@interface myController : UITableViewController {

}

@property (nonatomic, retain) NSArray *samples
@end

@implementation
   -(NSArray*) samples {
    //you can for example read some array from file and return it
   }

   -(void) setSamples:(NSArray*) arr {
     //write that array to file or whatever you want
    }
@end

With new compiler you can use properties without ivars at all, compiler will generate them for you implicitly.

Upvotes: 3

Related Questions