ios 在初始化时将参数传递给自定义类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6084802/
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-30 20:03:10  来源:igfitidea点击:

Passing parameters to a custom class on initialization

objective-ccocoa-touchiosinit

提问by user567

I have a class Messagewith two attributes, nameand message, and another class MessageControllerwith two text fields, nameFieldand messageField. I want to make an instance of Messagein MessageController, passing these two attributes as arguments.

我有一个Message有两个属性的类,namemessage,另一个MessageController有两个文本字段的类,nameFieldmessageField。我想创建一个Messagein实例MessageController,将这两个属性作为参数传递。

Right now, I am doing this:

现在,我正在这样做:

 Message *messageIns = [[Message alloc] init];
 messageIns.name = nameField;
 messageIns.message = MessageField; 

How can I pass the values at the creation of an instance? I tried to redefine initin Message.m, but I don't know how do that.

如何在创建实例时传递值?我试图init在 Message.m 中重新定义,但我不知道该怎么做。

-(id)init{
    if((self=[super init])){

    }
    return self;
}

Please help.

请帮忙。

回答by Giuliano Galea

You have to create a custom initializer.

您必须创建一个自定义初始化程序。

-(id)initWithName:(NSString *)name_ message:(NSString *)message_ 
{
     self = [super init];
     if (self) {
         self.name = name_;
         self.message = message_;
     }
     return self;
}

of course this assumes your parameters are of NSString type and that you have your properties set correctly ;)

当然,这假设您的参数是 NSString 类型,并且您的属性设置正确;)