I tend to use properties exclusively in my classes, especially now that you can declare properties in a class extension thanks to the modern Objective-C 2.0 runtime—I use this feature to create "private" properties.
My question is if there is any good reason to ever declare ivars in a class interface anymore. I prefer my public-facing interfaces to be as minimal and clean as possible, only revealing aspects of my class that are pertinent.
For example, I would tend to do the following:
MyClass.h
:
@interface MyClass : NSObject
@property (nonatomic, copy) NSString * publicString;
@property (nonatomic, copy, readonly) NSString * readOnlyString;
@end
MyClass.m
:
@interface MyClass ()
@property (nonatomic, copy, readwrite) NSString * readOnlyString;
@property (nonatomic, copy) NSString * privateString;
@end
@implementation MyClass
@synthesize publicString = publicString_;
@synthesize readOnlyString = readOnlyString_;
@synthesize privateString = privateString_;
- (void)init
{
self = [super init];
if (self != nil)
{
self.publicString = @"Public String";
self.readOnlyString = @"Read-Only String";
self.privateString = @"Private String";
}
return self;
}
- (void)dealloc
{
[publicString_ release];
[readOnlyString_ release];
[privateString_ release];
[super dealloc];
}
@end
Code style preferences aside, are there any issues with avoiding ivars entirely like this?
For a private/protected variable, use iVar; for a public variable, use property. If you want to use the benifit of property attributes for a private variable, like retain, nonatomic etc., declare the property in the implementation file as a private property. For an iVar, you can use @private , @protected and @public .
Accessing an ivar through a getter/setting involves an Objective-C method call, which is much slower (at least 3-4 times) than a "normal" C function call and even a normal C function call would already be multiple times slower than accessing a struct member.
I may have found an answer that's suitable enough for me to explicitly back my properties with ivars. It doesn't appear as if the debugger will list any automatically synthesized ivars, so there's no way to just drill through self
during debugging and check various values other than manually calling the property accessors, which is tedious. Unless they change this, this is probably more than enough reason for me to just go back to declaring ivars explicitly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With