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
Passing parameters to a custom class on initialization
提问by user567
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.
我有一个Message
有两个属性的类,name
和message
,另一个MessageController
有两个文本字段的类,nameField
和messageField
。我想创建一个Message
in实例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 init
in 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 类型,并且您的属性设置正确;)