设置数组中所有对象的bool 属性
Set bool property of all objects in the array
我有一个名为 PhotoItem
的模型 class。其中我有一个 BOOL
属性 isSelected
@interface PhotoItem : NSObject
/*!
* Indicates whether the photo is selected or not
*/
@property (nonatomic, assign) BOOL isSelected;
@end
我有一个 NSMutableArray
,它包含这个特定模型的对象。我想做的是,在一个特定的事件中,我想将数组中所有对象的bool 值设置为true 或false。我可以通过遍历数组并设置值来做到这一点。
而不是我尝试使用:
[_photoItemArray makeObjectsPerformSelector:@selector(setIsSelected:) withObject:[NSNumber numberWithBool:true]];
但我知道这行不通,但事实并非如此。此外,我不能将 true 或 false 作为其中的参数传递(因为它们不是对象类型)。因此,为了解决这个问题,我实现了一个自定义 public 方法,例如:
/*!
* 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]];
效果很好。但我的问题是,有没有更好的方法可以在不实现自定义 public 方法的情况下实现这一点?
Is there any better way to achieve this without implementing a custom public method?
这听起来像是在征求意见,所以这是我的意见:保持简单。
for (PhotoItem *item in _photoItemArray)
item.isSelected = YES;
当您可以编写任何人都能立即理解的代码时,为什么要通过晦涩的方法绕弯路混淆简单的事情?
做同样事情的另一种方法是:
[_photoItemArray setValue:@YES forKey:@"isSelected"];
这不需要额外的自定义 setter 方法,因为 KVC 会为您拆箱。
但我再次投票反对使用此类结构。我认为他们在分散您的注意力,使您无法理解简单的含义并使开发人员感到困惑。
我有一个名为 PhotoItem
的模型 class。其中我有一个 BOOL
属性 isSelected
@interface PhotoItem : NSObject
/*!
* Indicates whether the photo is selected or not
*/
@property (nonatomic, assign) BOOL isSelected;
@end
我有一个 NSMutableArray
,它包含这个特定模型的对象。我想做的是,在一个特定的事件中,我想将数组中所有对象的bool 值设置为true 或false。我可以通过遍历数组并设置值来做到这一点。
而不是我尝试使用:
[_photoItemArray makeObjectsPerformSelector:@selector(setIsSelected:) withObject:[NSNumber numberWithBool:true]];
但我知道这行不通,但事实并非如此。此外,我不能将 true 或 false 作为其中的参数传递(因为它们不是对象类型)。因此,为了解决这个问题,我实现了一个自定义 public 方法,例如:
/*!
* 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]];
效果很好。但我的问题是,有没有更好的方法可以在不实现自定义 public 方法的情况下实现这一点?
Is there any better way to achieve this without implementing a custom public method?
这听起来像是在征求意见,所以这是我的意见:保持简单。
for (PhotoItem *item in _photoItemArray)
item.isSelected = YES;
当您可以编写任何人都能立即理解的代码时,为什么要通过晦涩的方法绕弯路混淆简单的事情?
做同样事情的另一种方法是:
[_photoItemArray setValue:@YES forKey:@"isSelected"];
这不需要额外的自定义 setter 方法,因为 KVC 会为您拆箱。
但我再次投票反对使用此类结构。我认为他们在分散您的注意力,使您无法理解简单的含义并使开发人员感到困惑。