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

Mid*_* MP 2 boolean objective-c nsmutablearray ios

我有一个名为的模型类PhotoItem.我有一个BOOL属性isSelected

@interface PhotoItem : NSObject

/*!
 * Indicates whether the photo is selected or not
 */
@property (nonatomic, assign) BOOL isSelected;

@end
Run Code Online (Sandbox Code Playgroud)

NSMutableArray拥有这个特定模型的对象.我想要做的是,在特定情况下,我想将数组中所有对象的bool值设置为true或false.我可以通过迭代数组并设置值来做到这一点.

而不是我尝试使用:

[_photoItemArray makeObjectsPerformSelector:@selector(setIsSelected:) withObject:[NSNumber numberWithBool:true]];
Run Code Online (Sandbox Code Playgroud)

但我知道它不起作用,但事实并非如此.此外,我不能传递真或假作为参数(因为那些不是对象类型).因此,为了解决这个问题,我实现了一个自定义公共方法,如:

/*!
 * Used for setting the photo selection status
 * @param selection : Indicates the selection status
 */
- (void)setItemSelection:(NSNumber *)selection
{
    _isSelected = [selection boolValue];
}
Run Code Online (Sandbox Code Playgroud)

并称之为:

[_photoItemArray makeObjectsPerformSelector:@selector(setItemSelection:) withObject:[NSNumber numberWithBool:true]];
Run Code Online (Sandbox Code Playgroud)

它工作得很好.但我的问题是,如果没有实现自定义公共方法,有没有更好的方法来实现这一目标?

Nik*_*uhe 7

没有实现自定义公共方法,有没有更好的方法来实现这一目标?

这听起来像是在征求意见,所以这是我的:保持简单.

for (PhotoItem *item in _photoItemArray)
    item.isSelected = YES;
Run Code Online (Sandbox Code Playgroud)

当你编写任何人都能立即理解的代码时,为什么要通过晦涩的方法来绕道而行呢?

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

[_photoItemArray setValue:@YES forKey:@"isSelected"];
Run Code Online (Sandbox Code Playgroud)

这不需要自定义的附加setter方法,因为KVC会为您进行拆箱.

但我再次投票反对使用这样的结构.我认为它们会分散您的简单含义和混淆开发人员的注意力.