设置数组中所有对象的布尔属性 [英] Set bool property of all objects in the array

查看:21
本文介绍了设置数组中所有对象的布尔属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've a model class called PhotoItem. In which I have a BOOL property isSelected

@interface PhotoItem : NSObject

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

@end

我有一个 NSMutableArray 来保存这个特定模型的对象.我想要做的是,在特定事件中,我想将数组中所有对象的布尔值设置为 true 或 false.我可以通过遍历数组并设置值来做到这一点.

I've an NSMutableArray which holds the object of this particular model. What I want to do is, in a particular event I want to set the bool value of all objects in the array to true or false. I can do that by iterating over the array and set the value.

而不是我尝试使用:

[_photoItemArray makeObjectsPerformSelector:@selector(setIsSelected:) withObject:[NSNumber numberWithBool:true]];

但我知道它不会起作用,但它没有.此外,我不能将 true 或 false 作为参数传递(因为它们不是对象类型).所以为了解决这个问题,我实现了一个自定义的公共方法,比如:

But I know it won't work and it didn't. Also I can't pass true or false as the param in that (since those are not object type). So for fixing this issue, I implemented a custom public method like:

/*!
 * 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]];

效果很好.但我的问题是,有没有更好的方法可以在不实现自定义公共方法的情况下实现这一点?

It worked perfectly. But my question is, Is there any better way to achieve this without implementing a custom public method ?

推荐答案

有没有更好的方法在不实现自定义公共方法的情况下实现这一点?

Is there any better way to achieve this without implementing a custom public method?

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

This sounds like you are asking for opinion, so here is mine: Keep it simple.

for (PhotoItem *item in _photoItemArray)
    item.isSelected = YES;

既然您可以编写任何人都会立即理解的代码,为什么还要通过晦涩的方法来绕道而行来混淆简单的事情?

Why obfuscate a simple thing with detours through obscure methods when you can write code that anybody will immediately understand?

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

Another way of doing the same thing would be:

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

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

This does not need the custom additional setter method because KVC does the unboxing for you.

但我还是会投票反对使用这种结构.我认为他们分散了对简单含义的注意力,并使追随您的开发人员感到困惑.

But again I would vote against using such constructs. I think they are distracting from the simple meaning and confusing developers that come after you.

这篇关于设置数组中所有对象的布尔属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆