Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any reason to declare ivars if you're using properties exclusively in Objective-C?

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?

like image 949
CIFilter Avatar asked Feb 04 '11 22:02

CIFilter


People also ask

How do I declare iVar in Objective-C?

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 .

What is Ivars Objective-C?

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.


1 Answers

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.

like image 181
CIFilter Avatar answered Nov 30 '22 08:11

CIFilter