Search code examples
objective-cstructconstructorinitialization

How to initialize an Objective-C struct in constructor?


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.

How can I do this?


Solution

  • 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:

    For example

    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();
    

    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.