How can I add an opaque type to a collection in cocoa?
如何在可可中为集合添加opaque类型?
I get a compiler warning for this (obviously, because opaque types are not objects):
我得到了一个编译器警告(显然,因为opaque类型不是对象):
CGColorSpaceRef colorSpace;
NSArray *myArray = [NSArray arrayWithObject:colorSpace];
2 个解决方案
#1
You can use the NSValue class to wrap your opaque types in an object. From here:
您可以使用NSValue类将不透明类型包装在对象中。从这里:
An NSValue object is a simple container for a single C or Objective-C data item. It can hold any of the scalar types such as int, float, and char, as well as pointers, structures, and object ids. The purpose of this class is to allow items of such data types to be added to collections such as instances of NSArray and NSSet, which require their elements to be objects. NSValue objects are always immutable.
NSValue对象是单个C或Objective-C数据项的简单容器。它可以包含任何标量类型,如int,float和char,以及指针,结构和对象id。此类的目的是允许将此类数据类型的项添加到集合中,例如NSArray和NSSet的实例,这些集合要求其元素为对象。 NSValue对象始终是不可变的。
#2
CoreFoundation data types (CFTypes) can be directly added to collections. (They need to be cast to (id) to suppress warnings.) This is called "toll free bridging."
CoreFoundation数据类型(CFTypes)可以直接添加到集合中。 (他们需要被强制转换为(id)来抑制警告。)这被称为“免费桥接”。
CGColorSpaceRef colorSpace;
NSArray *myArray = [NSArray arrayWithObject:(id)colorSpace];
#1
You can use the NSValue class to wrap your opaque types in an object. From here:
您可以使用NSValue类将不透明类型包装在对象中。从这里:
An NSValue object is a simple container for a single C or Objective-C data item. It can hold any of the scalar types such as int, float, and char, as well as pointers, structures, and object ids. The purpose of this class is to allow items of such data types to be added to collections such as instances of NSArray and NSSet, which require their elements to be objects. NSValue objects are always immutable.
NSValue对象是单个C或Objective-C数据项的简单容器。它可以包含任何标量类型,如int,float和char,以及指针,结构和对象id。此类的目的是允许将此类数据类型的项添加到集合中,例如NSArray和NSSet的实例,这些集合要求其元素为对象。 NSValue对象始终是不可变的。
#2
CoreFoundation data types (CFTypes) can be directly added to collections. (They need to be cast to (id) to suppress warnings.) This is called "toll free bridging."
CoreFoundation数据类型(CFTypes)可以直接添加到集合中。 (他们需要被强制转换为(id)来抑制警告。)这被称为“免费桥接”。
CGColorSpaceRef colorSpace;
NSArray *myArray = [NSArray arrayWithObject:(id)colorSpace];