13

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.

3

5 Answers 5

34

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This response is outdated. As of WWDC '18, you are now allowed to specify ARC object pointers in C structs.
It appears that at least __strong and __weak are now supported in structs by clang (2019).
8

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
    ...
}

Comments

1

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;
};

Comments

0

I just integrated the same code into my project from the Google Toolbox for Mac

GTMNSString-HTML.m

Their suggestion for ARC Compatibility of adding the -fno-objc-arc flag to each file worked for me.

1 Comment

brother, did u use the above code for epub reader. If so pls guide me to convert it to arc. It would be extremely helpful for me....
0

As other commenter mentioned, as of XCode 10 this is now allowed. Previously the only way to have pointers to obj-c objects in a struct with ARC enabled was to use unsafe_unretained.

Note that even with these changes, it is still a bit risky though. You must take care to explicitly nil out any objc pointers before de-allocating a heap-allocated struct, or ARC will not be able to decrease the refcount for those.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.