Frage

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

?

War es hilfreich?

Lösung

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

Andere Tipps

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

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;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top