NSObject自定义init与对象/参数

时间:2013-10-03 11:18:22

标签: ios objective-c nsobject

我想要完成的事情就像是

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

然后在NSObject“Person”中,有类似的内容:

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

3 个答案:

答案 0 :(得分:26)

您的退货类型无效,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);

答案 1 :(得分:10)

像这样更改您的代码

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

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

答案 2 :(得分:0)

因此,您可以使用现代objective-c样式来获取关联数组值;)

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

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