objective-c primitive arrays
I want to have a mutable array with primitives in obj-c (selectors). What's the recommended way to do this? NSArray
and开发者_开发问答 those can only hold objects.
You should use an NSValue
to wrap the selector or any other primitive type you need. In Cocoa SEL is some kind of pointer, so you can use [NSValue valueWithPointer:whatever]
to construct it and [value pointerValue]
to get it out. Or, in general you can use [NSValue valueWithBytes:&whatever objCType:@encode(SEL)]
; this works for any type.
If you want to store an array of SEL
objects, the easiest thing would be to convert the SEL
s to NSString
s using the NSStringFromSelector()
function, store them in an NSMutableArray
, and then convert them back to SEL
s when you pull them out using NSSelectorFromString()
function.
Other than managing a C-style array yourself (which is definitely not the best option, IMO), your only option is to use NSArray
/NSMutableArray
, and store the numbers using NSNumber
. It's slightly more annoying to get the value out than with the actual numeric type, but it does free you from managing the array's memory yourself.
Since the primitive types are generally just numbers (be they integer or floating-point) or pointers, what's the problem with using the classes used to wrap those up for your purposes? An NSMutableArray
of NSNumbers
, for example?
精彩评论