Last active
October 15, 2021 19:17
-
-
Save theoknock/539928af4493d05aa46c380a8d4143e4 to your computer and use it in GitHub Desktop.
Enumerating objects using enumeration block with local scope property returned by an initializer block
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect { | |
__autoreleasing NSArray<UICollectionViewLayoutAttributes *> * collectionViewLayoutAttributes; | |
[[collectionViewLayoutAttributes = [[NSArray alloc] initWithArray:[super layoutAttributesForElementsInRect:rect] copyItems:TRUE] self] enumerateObjectsUsingBlock:^ (UICollectionViewLayoutAttributes * selected_attributes) { | |
return ^(UICollectionViewLayoutAttributes * _Nonnull attributes, NSUInteger idx, BOOL * _Nonnull stop) { | |
// Configure each attributes object in the collection individually | |
// based on the configuration of a single attributes object in that same collection | |
}; | |
}(^ UICollectionViewLayoutAttributes * (NSArray<NSIndexPath *> * visible_index_paths) { | |
UICollectionViewLayoutAttributes * selectedAttributes = nil; | |
for (NSIndexPath * indexPath in visible_index_paths) { | |
if ([[self.collectionView cellForItemAtIndexPath:indexPath] isSelected]) { | |
selectedAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath]; | |
break; | |
} | |
} | |
return selectedAttributes; | |
}([self.collectionView indexPathsForVisibleItems]))]; | |
return collectionViewLayoutAttributes; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The block supplied to the enumerateObjectsUsingBlock: parameter executes an initialization block that sets properties for subsequent execution by the caller (in this case, NSArray). The second block is executed once when the property is set; it is its return value that sets the property value that is the enumeration block. The enumeration block is, of course, set once, but it is executed for as many times as there are objects in the array.
In this example, an array of objects is being searched for a unique property value. When found, it is then passed as a property global to the enumeration block, but local to the caller.
In other words, the collection of objects to enumerate have a joint dependency on the state of one of the objects in that same collection.