设置数组中所有对象的布尔属性

我有一个名为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作为参数(因为那些不是对象types)。 所以为了解决这个问题,我实现了一个自定义的公共方法,如:

 /*! * 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 (PhotoItem *item in _photoItemArray) item.isSelected = YES; 

为什么用一些晦涩难懂的方法来绕过一个简单的东西,当你可以编写任何人立即可以理解的代码?

做同样事情的另一种方法是:

 [_photoItemArray setValue:@YES forKey:@"isSelected"]; 

这不需要自定义额外的setter方法,因为KVC为您做了拆箱。

但是我也会反对使用这样的结构。 我认为他们正在分散注意力的简单含义和混乱的开发者。