如何测试一个位标记的所有字段是否存在于另一个位掩码中?

iam*_*mer 0 c iphone objective-c ipad ios

例如,如果您具有类型UIUserNotificationType的位掩码,并按如下方式构造它们:

UIUserNotificationType a = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge;
UIUserNotificationType b = UIUserNotificationTypeAlert;
UIUserNotificationType c = UIUserNotificationTypeAlert | UIUserNotificationTypeSound;
Run Code Online (Sandbox Code Playgroud)

如何将一个字段与另一个字段匹配,以查看所有字段都包含在另一个字段中?

b已完全包含在其中,a且结果应为TRUE。 c未完全包含在其中a,应导致FALSE。

我知道如何测试一个特定字段的成员资格:BOOL match =(b&UIUserNotificationTypeAlert)!= 0;

这不起作用:

BOOL included = (a & b); // a includes b? (= YES)
included = (a & c); // a includes c? (= YES)
Run Code Online (Sandbox Code Playgroud)

要知道一个位掩码的所有字段是否都包含在另一个字段中,我必须if为每个可能的字段创建一个,然后像这样对它进行测试:

if (b & UIUserNotificationTypeAlert && !(a & UIUserNotificationTypeAlert)) {
    return NO;
}
if (b & UIUserNotificationTypeBadge && !(a & UIUserNotificationTypeBadge)) {
    return NO;
}
if (b & UIUserNotificationTypeSound && !(a & UIUserNotificationTypeSound)) {
    return NO;
}
return YES;
Run Code Online (Sandbox Code Playgroud)

这感觉不对。应该有一个更简单的方法。

Ale*_*exD 5

要测试mask b是否完全包含mask a,可以尝试bitwise and

if((b & a) == b)
Run Code Online (Sandbox Code Playgroud)