如何在构造函数中初始化Objective C结构? [英] How to initialize an Objective C struct in constructor?

查看:101
本文介绍了如何在构造函数中初始化Objective C结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Objective C上使用一种结构来存储一些数据,例如:

I´m using a struct on Objective C to store some data, something like this:



@interface Interface : NSObject
{
    // my Data
    struct Data
    {
        __unsafe_unretained BOOL isInit;
        __unsafe_unretained BOOL isRegister;
        __unsafe_unretained NSString* myValue;

       // Data() : isInit(false), isRegister(false), myValue(@"mYv4lue") {} // Constructor doesnt work
    };

    struct Data myData;  // Create Struct

}

但是我无法使用构造函数进行编译。我希望这些值在创建结构时采用默认值。

But I can't compile with a constructor. I want the values take some default value when I create the Struct.

我该怎么做?

推荐答案

结构没有初始化程序,如果要创建具有一组特定值的结构,则可以编写一个函数,该函数返回为您创建并初始化的函数:

Structs don't have initializers, if you want to create a struct with a particular set of values you could write a function that returns creates and initialises it for you:

例如

struct Data {
        BOOL isInit;
        BOOL isRegister;
        NSString* myValue;
};

Data MakeInitialData () {
    data Data;
    data.isInit = NO;
    data.isRegister = NO;
    data.myValue = @"mYv4lue";

    return data;
}

现在您可以通过以下方式获得正确设置的结构:

now you can get a correctly set up struct with:

Data newData = MakeInitialData();

不过是笔记;您似乎正在使用ARC,它不适用于其中包含对象指针的结构。在这种情况下,建议使用类而不是结构。

A note, though; you seem to be using ARC, which doesn't work well with structs that have object pointers in them. The recommendation in this case is to just use a class instead of a struct.

这篇关于如何在构造函数中初始化Objective C结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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