Oscar Apeland
Oscar Apeland

Reputation: 6662

NSObject custom init with object/parameters

What i'm trying to accomplish is something like

Person *person1 = [[Person alloc]initWithDict:dict];

and then in the NSObject "Person", have something like:

-(void)initWithDict:(NSDictionary*)dict{
    self.name = [dict objectForKey:@"Name"];
    self.age = [dict objectForKey:@"Age"];
    return (Person with name and age);
}

which then allows me to keep using the person object with those params. Is this possible, or do I have to do the normal

Person *person1 = [[Person alloc]init];
person1.name = @"Bob";
person1.age = @"123";

?

Upvotes: 12

Views: 24806

Answers (3)

Josep Escobar
Josep Escobar

Reputation: 456

So you can use modern objective-c style to get associative array values ;)

-(id)initWithDict:(NSDictionary*)dict
 {
    self = [super init];

    if(self)
    {       
      self.name = dict[@"Name"];
      self.age = dict[@"Age"];
    }
   return self;
}

Upvotes: 0

Hindu
Hindu

Reputation: 2924

Your return type is void while it should instancetype.

And you can use both type of code which you want....

Update:

@interface testobj : NSObject
@property (nonatomic,strong) NSDictionary *data;

-(instancetype)initWithDict:(NSDictionary *)dict;
@end

.m

@implementation testobj
@synthesize data;

-(instancetype)initWithDict:(NSDictionary *)dict{
self = [super init];
if(self)
{
   self.data = dict;
}
return self;
}

@end

Use it as below:

    testobj *tt = [[testobj alloc] initWithDict:@{ @"key": @"value" }];
NSLog(@"%@",tt.ss);

Upvotes: 27

zt9788
zt9788

Reputation: 958

change your code like this

-(id)initWithDict:(NSDictionary*)dict
 {
    self = [super init];

    if(self)
    {       
      self.name = [dict objectForKey:@"Name"];
      self.age = [dict objectForKey:@"Age"];
    }
   return self;
}

Upvotes: 10

Related Questions