Fixing ARC error when using Objective-C object in

2020-02-08 17:58发布

问题:

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.

回答1:

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.



回答2:

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


回答3:

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.



回答4:

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


标签: xcode