在 Objective C 中创建对象时如何初始化实例变量?

发布于 2024-10-25 01:36:01 字数 97 浏览 3 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

琴流音 2024-11-01 01:36:01

当您说初始化字典时,我假设您只想为其分配内存。如果是这样,您可以执行以下示例:

- (id) init {
    self = [super init];
    if (self != nil) {
        _privateDict = [[NSMutableDictionary alloc] initWithCapacity:40];
    }
    return self;
}

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:

- (id) init {
    self = [super init];
    if (self != nil) {
        _privateDict = [[NSMutableDictionary alloc] initWithCapacity:40];
    }
    return self;
}
高冷爸爸 2024-11-01 01:36:01

通常,您使用 init 方法。例如:

Myclass *anInstance = [[MyClass alloc] init];

某些类具有专门的初始化程序,可以接受参数。一个典型的例子是您实现的任何 UIViewController 子类。这看起来很熟悉吗?

MyUIViewController *viewController = [[MyUIViewController alloc] initWithNibNamed: @"MyUIViewController" bundle: nil];

请注意 initWithNibNamed 位。您也可以像这样编写自定义初始值设定项。我建议阅读其他人编写的代码。查找初始化程序并尝试了解它是如何编写/“设置”的。

要创建字典,您可以使用 NSDictionaryNSMutableDictionary。它们有几个初始化器。您可以使用 initWithObjects: ,然后传入一堆对象来存储在字典中。

Generally, you use the init method. For example:

Myclass *anInstance = [[MyClass alloc] init];

Some classes have specialized initializers that will take parameters. A classic example is any UIViewController subclass that you implement. Does this look familiar?

MyUIViewController *viewController = [[MyUIViewController alloc] initWithNibNamed: @"MyUIViewController" bundle: nil];

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 or NSMutableDictionary. Those have several initializers. You can use initWithObjects: and then pass in a bunch of objects to store in the dictionary.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文