Reputation: 3141
I would like to know if there is a better way to set each objects in a NSMutableArray a property value ?
//player.h
@interface Player : NSObject
@property BOOL isEliminated;
//test.h
@property NSMutableArray *players;
//test.m
for(Player *p in self.players)
{
p.isEliminated = NO;
}
I am pretty new to xCode and I have a C# background. I know C# & Linq can provide a non-loop solution.. I would like to know if this is also possible with Objective C
I search here and there... All I could found is a way to get objects from array where property X equals somevalue..
Upvotes: 0
Views: 83
Reputation: 25459
You can use makeObjectsPerformSelector: method on NSMutableArray to set change value of all object in NSMutableArray:
[self.players makeObjectsPerformSelector:@selector(setIsEliminated:) withObject:@NO];
Upvotes: 0
Reputation: 49386
Well, you can create one loopless solution with blocks and NSArray
s - (void)enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block
message. Something like:
[self.players enumerateObjectsUsingBlock:^(Player *p, NSUInteger idx, BOOL *stop) {
p.isEliminated = NO;
}];
However, this is hardly more readable. Using a loop for this type of work is, in my opinion, fine.
Upvotes: 0
Reputation: 540105
With Key-Value Coding:
[self.players setValue:@NO forKey:@"isEliminated];
sets the property on each element of the array.
Note that even though the property is a (scalar) BOOL
, you have to use the Objective-C
number object @NO
here. It is automatically "translated" to NO
when setting the
property.
Upvotes: 6