根据枚举属性过滤NSMutableArray

18

我有一个包含“GameObject”对象的NSMutableArray。GameObject有许多属性,其中之一是“gameObjectType”。"gameObjectType"是GameObjectTypeEnum类型。我想过滤这个NSMutableArray,只返回某种类型的游戏对象。我已经做了以下工作,但它给了我一个“BAD ACCESS”错误:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"gameObjectType = %@", gameObjectType];
return [gameObjects filteredArrayUsingPredicate:predicate];

在predicateWithFormat调用中是否可以传递“自定义”类型(即我定义的这个枚举)?

2个回答

22

字符串格式说明符 %@ 表示一个对象,但你正在传递一个整数值。你可能想将 gameObjectType 强制转换为 int 并使用 %d 说明符。查看字符串格式说明符了解更多信息。


强制转换为int并使用%d给了我所需的!谢谢。 - Marty

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];
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接