初始化时将参数传递给自定义类 [英] Passing parameters to a custom class on initialization

查看:139
本文介绍了初始化时将参数传递给自定义类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个消息,有两个属性, name message 和另一个类具有两个文本字段 nameField messageField / code>。
我想在 MessageController 中创建一个 Message 的实例,传递这两个属性作为参数。 p>

现在,我这样做:

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

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

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

}
return self;
}

请帮助。

   - (id)initWithName:必须创建一个自定义初始化程序。 (NSString *)name_ message:(NSString *)message_ 
{
self = [super init];
if(self){
self.name = name_;
self.message = message_;
}
return self;
}

当然这假定你的参数是NSString类型,设置正确;)


I have a class Message with two attributes, name and message, and another class MessageController with two text fields, nameField and messageField. I want to make an instance of Message in MessageController, passing these two attributes as arguments.

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 init in Message.m, but I don't know how do that.

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

    }
    return self;
}

Please help.

解决方案

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

这篇关于初始化时将参数传递给自定义类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆