在 Objective C 中创建对象时如何初始化实例变量?
在 C++ 中,我会在构造函数中执行此操作,但在 Objective CI 上,我不知道应该如何初始化它。
例如,我有一个必须是字典的成员变量,我想初始化这个字典。
In C++ I would do this in the constructor, but on Objective C I do not know how I am supposed to initialize it.
For example I have a member variable that has to be a dictionary and I want to initialize this dictionary.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您说初始化字典时,我假设您只想为其分配内存。如果是这样,您可以执行以下示例:
When you say initialize the dictionary, I am assuming you just want to allocate memory for it. If so you can do the following sample:
通常,您使用
init
方法。例如:某些类具有专门的初始化程序,可以接受参数。一个典型的例子是您实现的任何 UIViewController 子类。这看起来很熟悉吗?
请注意
initWithNibNamed
位。您也可以像这样编写自定义初始值设定项。我建议阅读其他人编写的代码。查找初始化程序并尝试了解它是如何编写/“设置”的。要创建字典,您可以使用
NSDictionary
或NSMutableDictionary
。它们有几个初始化器。您可以使用initWithObjects:
,然后传入一堆对象来存储在字典中。Generally, you use the
init
method. For example:Some classes have specialized initializers that will take parameters. A classic example is any UIViewController subclass that you implement. Does this look familiar?
Notice the
initWithNibNamed
bit. You can write custom initializer like that as well. I suggest reading code that others wrote. Look for the initializer and try to understand how it was written/"set up".To make a dictionary, you can use
NSDictionary
orNSMutableDictionary
. Those have several initializers. You can useinitWithObjects:
and then pass in a bunch of objects to store in the dictionary.您应该阅读 - The Objective-C 编程语言:分配和初始化对象
You should read - The Objective-C Programming Language: Allocating and Initializing Objects