Swapnil Kotwal
Swapnil Kotwal

Reputation: 5730

How to pass object as a parameter to new class constructor in objective c?

I'm pretty new with objective c. I have instantiated 'myClass' object in ViewController.m file.

MyClass myClass = [[MyClass alloc]init];

I have to pass this 'myClass' object to new class constructor(say Person class) as a parameter.

How could I implement this and use same 'myClass' object in Person class?

Thanks.

Upvotes: 2

Views: 5174

Answers (3)

manujmv
manujmv

Reputation: 6445

You have to instantiated like below

MyClass *myClass = [[MyClass alloc]init];

in your Person class declare a variable,

MyClass *class;

create method,

- (id) initWithClass:(MyClass *)myClass{
    self = [super init];
    if (self) {
        self.class= myClass;
    }    
    return self;
}

initialize the person class as

Person *person = [[Person alloc] initWithClass:myClass];

Upvotes: 2

sunkehappy
sunkehappy

Reputation: 9101

You can just add an initWithXXX method like this:

@interface Person : NSObject

- (id)initWithMyClass:(MyClass *)myClass;

@end

Upvotes: 0

Mujah Maskey
Mujah Maskey

Reputation: 8804

in your person class, make method like this

- (id) initWithMyClass:(MyClass *)m{
    self = [super init];
    if (self) {
        self.myclass= m;
    }    
    return self;
}

now you can call it like

Person *person = [[Person alloc] initWithMyClass:myClass];//using your variable here

Upvotes: 0

Related Questions