The elegance of the Block
This show how to use an inline block to better organize your code. Isn’t this more elegant? You can clearly see all the instruction that lead to the UICollectionView initialization.
__weak typeof(self) weakSelf = self;
self.collectionView = (UICollectionView *)^{
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:weakSelf.view.bounds
collectionViewLayout:flowLayout];
collectionView.delegate = weakSelf;
collectionView.dataSource = weakSelf;
return collectionView;
}();
Written by Luca Bernardi
Related protips
2 Responses
You do not need weakSelf here. The block lies on the stack, you do not pass it to anywhere or return from a method. So it is not copied to heap and it does not retain variables. Moreover it will be destroyed when method finishes. Just use self.
over 1 year ago
·
@rabovik you're right. It's not necessary but it's not an error; in the past I've been burned by a retain cycle caused by a block so I force myself to always use a weak self every time I access self inside a block, consider this like trying to forming an habit.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Block
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#