NSObject custom init with object/parameters

Oscar Apeland picture Oscar Apeland · Oct 3, 2013 · Viewed 23k times · Source

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";

?

Answer

Hindu picture Hindu · Oct 3, 2013

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);