ios 带有对象/参数的 NSObject 自定义初始化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19157827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 02:00:08  来源:igfitidea点击:

NSObject custom init with object/parameters

iosobjective-cnsobject

提问by Oscar Apeland

What i'm trying to accomplish is something like

我想要完成的是

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

and then in the NSObject"Person", have something like:

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

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

?

?

回答by Hindu

Your return type is void while it should instancetype.

您的返回类型是 void 而它应该是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

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

回答by zt9788

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

回答by Josep Escobar

So you can use modern objective-c style to get associative array values ;)

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

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

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