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.
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
...
}
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.
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;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With