Vincent Monteil
Vincent Monteil

Reputation: 578

Custom Constructor in Objective-C

I have created a custom class extending UIView. This class has some methods such as Drawerect...

Up to now, I was just putting it in my storyboard and telling that it belongs to the class. I would now allocate and place those objects dynamically. Is there a method so I could call :

[[MyObj alloc] initWithFrame:....] 

Id be glad to find any help !

Upvotes: 1

Views: 5596

Answers (2)

Maurice
Maurice

Reputation: 1464

You can create your own constructor in the header file of your class. The return value is of type id , in its declaration in the main file you need to call a super initialization (for example self = [super initWithFrame:CGRect]) and then return the self. You can customize the parameters of your constructor in the header file to fit your needs.

Example for UIView:

.h:

#import <UIKit/UIKit.h>
@interface CustomView : UIView
-(id)initWithFrame:(CGRect)frame backgroundColor:(UIColor *)backgroundColor;

.m:

#import "CustomView.h"

@implementation CustomView
-(id)initWithFrame:(CGRect)frame backgroundColor:(UIColor *)backgroundColor{

self = [super initWithFrame:frame];

if (self) {

//after allocation you could set variables:

self.backgroundColor = backgroundColor;

}

return self;
}

@end

Upvotes: 8

jlehr
jlehr

Reputation: 15617

When instances of UIView are unarchived from an Interface Builder document, their initWithFrame: method isn't called. Instead, the unarchiver calls initWithCoder:. Ideally you should override both methods, and have them call a common method that provides a shared implementation of the initialization code. That way the views will be initialized correctly whether they're instantiated programmatically, or as a result of being unarchived. Here's an example:

- (id)initWithFrame:(CGRect)frame
{
    if (!(self = [super initWithFrame:frame])) return nil;
    [self configureSubviews];
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    if (!(self = [super initWithCoder:aDecoder])) return nil;
    [self configureSubviews];
    return self;
}

- (void)configureSubviews
{
    // Custom configuration code...
}

Upvotes: 3

Related Questions