39

我需要在objective-c中使用一组布尔值。我已经基本设置好了,但是编译器在以下语句中抛出警告:

[updated_users replaceObjectAtIndex:index withObject:YES];

我敢肯定,这是因为 YES 根本不是一个对象。这是一个原始的。无论如何,我需要这样做,并且非常感谢有关如何完成它的建议。

谢谢。

4

6 回答 6

73

是的,这正是它的本质:NS* 容器只能存储 Objective-C 对象,而不是原始类型。

您应该能够通过将其包装在 NSNumber 中来完成您想要的:

[updated_users replaceObjectAtIndex:index withObject:[NSNumber numberWithBool:YES]]

或使用@(YES)which 将 a 包裹BOOL在 anNSNumber

[updated_users replaceObjectAtIndex:index withObject:@(YES)]]

然后,您可以拉出 boolValue:

BOOL mine = [[updated_users objectAtIndex:index] boolValue];

于 2009-03-09T22:57:13.910 回答
14

假设您的数组包含有效对象(并且不是 c 样式数组):

#define kNSTrue         ((id) kCFBooleanTrue)
#define kNSFalse        ((id) kCFBooleanFalse)
#define NSBool(x)       ((x) ? kNSTrue : kNSFalse)

[updated_users replaceObjectAtIndex:index withObject:NSBool(YES)];
于 2009-03-09T22:56:23.490 回答
12

您可以存储NSNumbers

[updated_users replaceObjectAtIndex:index
                         withObject:[NSNumber numberWithBool:YES]];

或使用 C 数组,具体取决于您的需要:

BOOL array[100];
array[31] = YES;
于 2009-03-09T22:56:06.580 回答
8

就像 Georg 所说,使用 C 数组。

BOOL myArray[10];

for (int i = 0; i < 10; i++){
  myArray[i] = NO;
}

if (myArray[2]){
   //do things;
}

Martijn,“myArray”是您使用的名称,在georg 的示例中为“array”。

于 2010-12-08T15:08:47.727 回答
4

从 XCode 4.4 开始,您可以使用 Objective-C 文字。

[updated_users replaceObjectAtIndex:index withObject:@YES];

哪里@YES相当于[NSNumber numberWithBool:YES]

于 2013-04-24T13:33:52.640 回答
1

如果您的集合很大或者您希望它比 objc 对象更快,请尝试 CoreFoundation 中的CFBitVector/CFMutableBitVector类型。它是 CF-Collections 类型之一,不附带NS 对应物,但如果需要,它可以快速包装在 objc 类中。

于 2012-04-04T05:19:52.887 回答