NSObject自定义init与对象/参数

Osc*_*and 12 objective-c nsobject ios

我想要完成的是类似的东西

Person *person1 = [[Person alloc]initWithDict:dict];
Run Code Online (Sandbox Code Playgroud)

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

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

然后,我允许我继续使用人物对象与那些参数.这是可能的,还是我必须正常做

Person *person1 = [[Person alloc]init];
person1.name = @"Bob";
person1.age = @"123";
Run Code Online (Sandbox Code Playgroud)

Hin*_*ndu 27

你的返回类型是空的instancetype.

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

更新:

@interface testobj : NSObject
@property (nonatomic,strong) NSDictionary *data;

-(instancetype)initWithDict:(NSDictionary *)dict;
@end
Run Code Online (Sandbox Code Playgroud)

.M

@implementation testobj
@synthesize data;

-(instancetype)initWithDict:(NSDictionary *)dict{
self = [super init];
if(self)
{
   self.data = dict;
}
return self;
}

@end
Run Code Online (Sandbox Code Playgroud)

使用方法如下:

    testobj *tt = [[testobj alloc] initWithDict:@{ @"key": @"value" }];
NSLog(@"%@",tt.ss);
Run Code Online (Sandbox Code Playgroud)


zt9*_*788 10

像这样改变你的代码

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

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

  • @Monolo :)我的英语不是很好,句子太复杂,可能会让人不懂~~ (3认同)