Bernard
Bernard

Reputation: 4580

How to allocate memory for an array in class in objective-C?

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

  1. Allocate memory for the array.
  2. 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:

http://www.techotopia.com/index.php/An_Overview_of_Objective-C_Object_Oriented_Programming#Declaring.2C_Initializing_and_Releasing_a_Class_Instance

https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/DefiningClasses/DefiningClasses.html#//apple_ref/doc/uid/TP40011210-CH3-SW7

https://developer.apple.com/library/ios/releasenotes/ObjectiveC/ModernizationObjC/AdoptingModernObjective-C/AdoptingModernObjective-C.html#//apple_ref/doc/uid/TP40014150-CH1-SW11

Upvotes: 1

Views: 643

Answers (1)

trojanfoe
trojanfoe

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

Related Questions