HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Is this a correct way to write a convenience constructor?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thiswaywriteconstructorcorrectconvenience

Problem

I was reading more about the instancetype on Stack Overflow and now my question is:

For every convenience constructor that I write, do I need to have the corresponding one using init?

For example:

RandomItem.h

#import 

@interface RandomItem : NSObject

@property (nonatomic, copy) NSString *aString;

+(instancetype)itemWithString:(NSString *)string;

@end


RandomItem.m

#import "RandomItem.h"

@implementation RandomItem

+(instancetype)itemWithString:(NSString *)string
{
    RandomItem *anItem = [[self alloc] init];
    anItem.aString = string;
    return anItem;
}

@end


And compare this when using an -initWithString: constructor as well:

RandomItem.h

#import 

@interface RandomItem : NSObject

@property (nonatomic, copy) NSString *aString;

-(id)initWithString:(NSString *)string;
+(instancetype)itemWithString:(NSString *)string;

@end


RandomItem.m:

#import "RandomItem.h"

@implementation RandomItem

-(id)initWithString:(NSString *)string
{
    self = [super init];
    if (self)
    {
        self.aString = string;
    }
    return self;
}

+(instancetype)itemWithString:(NSString *)string
{
    return [[self alloc] initWithString:string];
}

@end


I suppose that both cases are fine, but I would like to hear your comments.

Thanks!

Solution

Personally I would prefer the second option because it makes it easier/less weird for subclasses to use and override alloc-init.

As a side node I would point to some reasons to reconsider user properties in your constructors.

  • Should I refer to self.property in the init method with ARC?



  • Friday Q&A 2009-11-27: Using Accessors in Init and Dealloc



  • Don’t Message self in Objective-C init (or dealloc)

Context

StackExchange Code Review Q#28545, answer score: 2

Revisions (0)

No revisions yet.