Setting default values for inherited property without using accessor in Objective-C?

Posted by Ben Stock on Stack Overflow See other posts from Stack Overflow or by Ben Stock
Published on 2014-05-30T02:48:04Z Indexed on 2014/05/30 3:26 UTC
Read the original article Hit count: 219

I always see people debating whether or not to use a property's setter in the -init method. I don't know enough about the Objective-C language yet to have an opinion one way or the other. With that said, lately I've been sticking to ivars exclusively. It seems cleaner in a way. I don't know. I digress. Anyway, here's my problem … Say we have a class called Dude with an interface that looks like this:

@interface Dude : NSObject {
    @private
    NSUInteger _numberOfGirlfriends;
}

@property (nonatomic, assign) NSUInteger numberOfGirlfriends;

@end

And an implementation that looks like this:

@implementation Dude

- (instancetype)init
{
    self = [super init];
    if (self) {
        _numberOfGirlfriends = 0;
    }
}

@end

Now let's say I want to extend Dude. My subclass will be called Playa. And since a playa should have mad girlfriends, when Playa gets initialized, I don't want him to start with 0; I want him to have 10. Here's Playa.m:

@implementation Playa

- (instancetype)init
{
    self = [super init];
    if (self) {

        // Attempting to set the ivar directly will result in the compiler saying, 
        // "Instance variable `_numberOfGirlfriends` is private."

        // _numberOfGirlfriends = 10; <- Can't do this.

        // Thus, the only way to set it is with the mutator:
        self.numberOfGirlfriends = 10;

        // Or: [self setNumberOfGirlfriends:10];
    }
}

@end

So what's a Objective-C newcomer to do? Well, I mean, there's only one thing I can do, and that's set the property. Unless there's something I'm missing. Any ideas, suggestions, tips, or tricks?

Sidenote: The other thing that bugs me about setting the ivar directly — and what a lot of ivar-proponents say is a "plus" — is that there are no KVC notifications. A lot of times, I want the KVC magic to happen. 50% of my setters end in [self setNeedsDisplay:YES], so without the notification, my UI doesn't update unless I remember to manually add -setNeedsDisplay. That's a bad example, but the point stands. I utilize KVC all over the place, so without notifications, things can act wonky.

Anyway, any info is much appreciated. Thanks!

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about initialization