[ACCEPTED]-How to initialize an Objective-C struct in constructor?-initialization

Accepted answer
Score: 24

Structs don't have initializers, if you 9 want to create a struct with a particular 8 set of values you could write a function 7 that returns creates and initialises it 6 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 5 set up struct with:

Data newData = MakeInitialData();

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

Score: 7

You could initialize a struct as follows 1 using static object for default settings.

typedef struct
{
    BOOL isInit;
    BOOL isRegister;
    __unsafe_unretained NSString* myValue;

} Data;
static Data dataInit = { .isInit = NO, .isRegister = NO, .myValue = @"mYv4lue"};

Data myCopyOfDataInitialized = dataInit;
Score: 3

The space where you're doing this -- between 8 curly braces at the beginning of the class's 7 @interface block -- doesn't allow running code. It 6 is solely for declarations of ivars. You 5 really shouldn't even be declaring structs in 4 there (I'm surprised that compiles).

Move 3 the constructor call to your class's init method. That's 2 where initialization of ivars is supposed 1 to happen in ObjC.

Score: 3

You can also do this way:

@interface Interface : NSObject
{

   typedef struct tagData

    {
        __unsafe_unretained BOOL isInit;
        __unsafe_unretained BOOL isRegister;
        __unsafe_unretained NSString* myValue;

        tagData(){
           isInit = NO;
           isRegister = NO;
           myValue = NULL;
        }
    } myData;

}

0

More Related questions