Reputation: 4580
I am very much new to objective-c and I'm struggling with this problem for a while! Here is my class prototype:
@interface YoCatchModel : NSObject
/**
Name of the Yo user. Currently this is local
*/
@property (nonatomic, strong) NSString* username;
/**
History of the messages sent with Yo
*/
@property (nonatomic, strong, readonly) NSMutableArray* historyArray;
/*
implement init method
*/
+ (instancetype) initmethod;
I should allocate memory for my history mutable array in this method which is read only.
I want to make another init method that takes a username string parameter. This new initWithUsername method should call init within its definition.
And here is implementation which I am trying to implement an init method using instancetype as the return type. But I am not really sure how to
Call another init method for the user name.
@implementation YoCatchModel
+ (instancetype)initmethod {
return [[[self class] alloc] init];
}
I appreciate if anyone can give me some hint how to do this. So far I have read these pages to get to here:
Upvotes: 1
Views: 643
Reputation: 122391
The initWithUsername
method becomes the designated initializer of your class and would look something like:
- (instancetype)initWithUsername:(NSString *)username
{
self = [super init];
if (self) {
_username = [username copy];
_historyArray = [NSMutableArray new];
}
return self;
}
You should make the default init
method use the designated initializer:
- (instancetype)init
{
return [self initWithUsername:nil];
}
and note that this code works on the property backing instance variables, which start with _
, rather than using self.
(which won't work with a readonly
property anyway), and this is to avoid possible KVO side-effects of the property setter methods.
Upvotes: 2