根据枚举属性过滤NSMutableArray

Mar*_*rty 18 objective-c

我有一个NSMutableArray填充了"GameObject"类型的对象.GameObject有许多属性,其中一个是"gameObjectType"."gameObjectType"的类型为GameObjectTypeEnum.我希望能够过滤此NSMutableArray,因此只返回某种类型的GameObjects.我已经有了以下内容,但它给了我一个"BAD ACCESS"错误:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"gameObjectType = %@", gameObjectType];
return [gameObjects filteredArrayUsingPredicate:predicate];
Run Code Online (Sandbox Code Playgroud)

是否可以将"自定义"类型(即我已定义的枚举)传递给predicateWithFormat调用?

Chu*_*uck 22

字符串格式说明符%@表示一个对象,而您传递的是整数值.您可能希望将gameObjectType强制转换为an int并使用说明%d符.有关详细信息,请查看字符串格式说明符.


Yun*_*hel 7

- (NSArray *)arrayFilteredByType:(enumType)type {

     //type is an NSUInteger property of the objects in the array 
     NSPredicate *predicate = [NSPredicate predicateWithFormat:@"type = %d", type];
     return [self.array filteredArrayUsingPredicate:predicate];
}
Run Code Online (Sandbox Code Playgroud)