12

我想要完成的是

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

然后在NSObject“人”中,有类似的东西:

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

然后,我可以继续使用带有这些参数的 person 对象。这可能吗,还是我必须做正常的

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

?

4

3 回答 3

27

您的返回类型应该是无效的instancetype

你可以使用你想要的两种类型的代码......

更新:

@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

如下使用它:

    testobj *tt = [[testobj alloc] initWithDict:@{ @"key": @"value" }];
NSLog(@"%@",tt.ss);
于 2013-10-03T11:25:56.060 回答
10

像这样更改您的代码

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

    if(self)
    {       
      self.name = [dict objectForKey:@"Name"];
      self.age = [dict objectForKey:@"Age"];
    }
   return self;
}
于 2013-10-03T11:29:57.307 回答
0

所以你可以使用现代的objective-c风格来获取关联数组值;)

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

    if(self)
    {       
      self.name = dict[@"Name"];
      self.age = dict[@"Age"];
    }
   return self;
}
于 2016-05-03T14:42:02.117 回答