xcode 在结构中使用 Objective-C 对象时修复 ARC 错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14784973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fixing ARC error when using Objective-C object in struct
提问by Seth bollenbecker
I am having an issue with my Xcode project.
我的 Xcode 项目有问题。
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.
ARC 禁止在结构或联合中使用 Objective-C 对象。
How can I fix it?
我该如何解决?
I cannot seem to find how this violates ARC but I would love to learn.
我似乎无法找到这如何违反 ARC,但我很想学习。
回答by bitmapdata.com
Change it to:
将其更改为:
typedef struct
{
__unsafe_unretained NSString *escapeSequence;
unichar uchar;
}MyStruct;
But, I recommend following Apple rules from this documentation.
但是,我建议遵循此文档中的Apple 规则。
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.
ARC 执行新规则
不能在 C 结构中使用对象指针。
您可以创建一个 Objective-C 类来管理数据,而不是使用结构体。
回答by lu_zero
The safest way is to use __unsafe_unretained
or directly CFTypeRef
and then use the __bridge
, __bridge_retained
and __bridge_transfer
.
最安全的方法是__unsafe_unretained
直接使用或CFTypeRef
然后使用__bridge
,__bridge_retained
和__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
...
}
回答by Anil Gupta
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
.
当我们在启用 ARC 的情况下在 Objective C 中定义 C 结构时,我们收到错误“ARC 禁止结构中的 Objective-C 对象”。在这种情况下,我们需要使用关键字__unsafe_unretained
。
Example
例子
struct Books{
NSString *title;
NSString *author;
NSString *subject;
int book_id;
};
Correct way to use in ARC enable projects:
在 ARC 启用项目中使用的正确方法:
struct Books{
__unsafe_unretained NSString *title;
__unsafe_unretained NSString *author;
__unsafe_unretained NSString *subject;
int book_id;
};
回答by foldinglettuce
I just integrated the same code into my project from the Google Toolbox for Mac
我刚刚从 Google Toolbox for Mac 将相同的代码集成到我的项目中
Their suggestion for ARC Compatibilityof adding the -fno-objc-arc
flag to each file worked for me.
他们建议将标志添加到每个文件的ARC 兼容性-fno-objc-arc
对我有用。