如何在构造函数中初始化 Objective-C 结构? [英] How to initialize an Objective-C struct in constructor?
问题描述
我在 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 没有初始化器,如果你想用一组特定的值创建一个结构体,你可以编写一个返回的函数,为你创建并初始化它:
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屋!