【发布时间】:2016-01-05 23:05:35
【问题描述】:
我有一个名为 PhotoItem 的模型类。其中我有一个BOOL 属性isSelected
@interface PhotoItem : NSObject
/*!
* Indicates whether the photo is selected or not
*/
@property (nonatomic, assign) BOOL isSelected;
@end
我有一个NSMutableArray,它保存了这个特定模型的对象。我想要做的是,在特定事件中,我想将数组中所有对象的布尔值设置为 true 或 false。我可以通过遍历数组并设置值来做到这一点。
而不是我尝试使用:
[_photoItemArray makeObjectsPerformSelector:@selector(setIsSelected:) withObject:[NSNumber numberWithBool:true]];
但我知道它不会起作用,但它没有。此外,我不能将 true 或 false 作为其中的参数传递(因为它们不是对象类型)。所以为了解决这个问题,我实现了一个自定义的公共方法,比如:
/*!
* Used for setting the photo selection status
* @param selection : Indicates the selection status
*/
- (void)setItemSelection:(NSNumber *)selection
{
_isSelected = [selection boolValue];
}
然后这样称呼它:
[_photoItemArray makeObjectsPerformSelector:@selector(setItemSelection:) withObject:[NSNumber numberWithBool:true]];
效果很好。但我的问题是,有没有更好的方法可以在不实现自定义公共方法的情况下实现这一点?
【问题讨论】:
-
您是否尝试在对象数组上使用“for 循环”?
-
我认为你走对了。
-
旁注:该属性的
isSelected名称似乎有点奇怪。 Apple 使用一种方案,其中布尔属性用一个简单的形容词命名,并且有一个使用“is”前缀的 setter name,例如@property (getter=isSelected) BOOL selected;。这甚至记录在 KVC 指南中,解释如何解析密钥。
标签: ios objective-c boolean nsmutablearray