Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

?

like image 262
Oscar Apeland Avatar asked Oct 03 '13 11:10

Oscar Apeland


1 Answers

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);
like image 163
Hindu Avatar answered Sep 22 '22 13:09

Hindu