Set bool property of all objects in the array

烂漫一生 提交于 2019-11-28 05:43:03

问题


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

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.

Instead of that I tried using:

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

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];
}

And calling it like:

[_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 ?


回答1:


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"];

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.



来源:https://stackoverflow.com/questions/33013868/set-bool-property-of-all-objects-in-the-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!