Objective C 布尔数组
我需要在 Objective-C 中使用一系列布尔值。 我已经基本设置完毕,但是编译器在以下语句中抛出警告:
[updated_users replaceObjectAtIndex:index withObject:YES];
我确信这是因为 YES 根本不是一个对象; 这是一个原始的。 无论如何,我需要这样做,并且非常感谢有关如何完成它的建议。
谢谢。
I need to utilize an array of booleans in objective-c. I've got it mostly set up, but the compiler throws a warning at the following statement:
[updated_users replaceObjectAtIndex:index withObject:YES];
This is, I'm sure, because YES is simply not an object; it's a primitive. Regardless, I need to do this, and would greatly appreciate advice on how to accomplish it.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
是的,事实就是如此:NS* 容器只能存储 Objective-C 对象,而不能存储原始类型。
您应该能够通过将其包装在 NSNumber 中来完成您想要的任务:
[updated_users ReplaceObjectAtIndex:index withObject:[NSNumber numberWithBool:YES]]
或使用
@(YES)
code> 将BOOL
包装在NSNumber
中[updated_users ReplaceObjectAtIndex:index withObject:@(YES)]]
然后您可以提取 boolValue :
BOOL 我的 = [[updated_users objectAtIndex:index] boolValue];
Yep, that's exactly what it is: the NS* containers can only store objective-C objects, not primitive types.
You should be able to accomplish what you want by wrapping it up in an NSNumber:
[updated_users replaceObjectAtIndex:index withObject:[NSNumber numberWithBool:YES]]
or by using
@(YES)
which wraps aBOOL
in anNSNumber
[updated_users replaceObjectAtIndex:index withObject:@(YES)]]
You can then pull out the boolValue:
BOOL mine = [[updated_users objectAtIndex:index] boolValue];
假设您的数组包含有效对象(并且不是 C 样式数组):
Assuming your array contains valid objects (and is not a c-style array):
您可以存储
NSNumbers
:或使用 C 数组,具体取决于您的需求:
You can either store
NSNumbers
:or use a C-array, depending on your needs:
正如 Georg 所说,使用 C 数组。
Martijn,“myArray”是您使用的名称,在 georg 的示例中为“array”。
Like Georg said, use a C-array.
Martijn, "myArray" is the name you use, "array" in georg's example.
从 XCode 4.4 开始,您可以使用 Objective-C 文字。
[updated_users ReplaceObjectAtIndex:index withObject:@YES];
其中
@YES
相当于[NSNumber numberWithBool:YES]
From XCode 4.4 you can use Objective-C literals.
[updated_users replaceObjectAtIndex:index withObject:@YES];
Where
@YES
is equivalent of[NSNumber numberWithBool:YES]
如果您的集合很大或者您希望它比 objc 对象更快,请尝试 CoreFoundation 中的
CFBitVector
/CFMutableBitVector
类型。 它是 CF-Collections 类型之一,不与 NS 对应项一起提供,但如果需要,它可以快速包装在 objc 类中。If your collection is large or you want it to be faster than objc objects, try the
CFBitVector
/CFMutableBitVector
types found in CoreFoundation. It's one of the CF-Collections types which does not ship with a NS counterpart, but it can be wrapped in an objc class quickly, if desired.