Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixing ARC error when using Objective-C object in struct

Tags:

xcode

I am having an issue with my Xcode project.

I have these lines:

typedef struct
{
    NSString *escapeSequence;
    unichar uchar;
}

and I am getting this error:

ARC forbids Objective-C objects in structs or unions.

How can I fix it?

I cannot seem to find how this violates ARC but I would love to learn.

like image 416
Seth bollenbecker Avatar asked Feb 09 '13 04:02

Seth bollenbecker


3 Answers

The safest way is to use __unsafe_unretained or directly CFTypeRef and then use the __bridge, __bridge_retained and __bridge_transfer.

e.g

typedef struct Foo {
    CFTypeRef p;
} Foo;

int my_allocating_func(Foo *f)
{
    f->p = (__bridge_retained CFTypeRef)[[MyObjC alloc] init];
    ...
}

int my_destructor_func(Foo *f)
{
    MyObjC *o = (__bridge_transfer MyObjC *)f->p;
    ...
    o = nil; // Implicitly freed
    ...
}
like image 71
lu_zero Avatar answered Oct 20 '22 12:10

lu_zero


Change it to:

typedef struct
{
    __unsafe_unretained NSString *escapeSequence;
    unichar uchar;
}MyStruct;

But, I recommend following Apple rules from this documentation.

ARC Enforces New Rules

You cannot use object pointers in C structures.
Rather than using a struct, you can create an Objective-C class to manage the data instead.

like image 38
bitmapdata.com Avatar answered Oct 20 '22 10:10

bitmapdata.com


When we are defining C structure in Objective C with ARC enable, we get the error "ARC forbids Objective-C objects in struct". In that case, we need to use keyword __unsafe_unretained.

Example

struct Books{

    NSString *title;
    NSString *author;
    NSString *subject;
    int book_id;
};

Correct way to use in ARC enable projects:

struct Books{

    __unsafe_unretained NSString *title;
   __unsafe_unretained NSString *author;
   __unsafe_unretained NSString *subject;
   int book_id;
};
like image 36
Anil Gupta Avatar answered Oct 20 '22 11:10

Anil Gupta