You really shouldn't add a backlink from a cell to CollectionView as an iVar or property, because you end up with a really (really) bad cross reference (objA points to objB and objB points to objA). Besides minor issues such as compilation errors (can be fixed poorly with @class operators), this also leads to serious problems such as objects that cannot be deleted, memory leak, zombies, etc.
Rule of thumb:
parents know about their children, but children should not know about their parents.
In other words: CollectionView knows its cells, but cells should not know their CollectionView.
Possible solutions
Recycle your task and your solution . Maybe add a gesture recognizer to the collection, not to the cell. There is -indexPathForItemAtPoint: to provide you with the selected cell.
If you absolutely need a backlink: define a protocol and use a delegate . This is a common design pattern in Cocoa / Cocoa Touch. You should read about the delegate design pattern, but in short, this is how you do it:
define the protocol in your cell (remember that the cell does not know about the type of the parent, defining this protocol, it knows for sure that there is one or more methods available in the "parent")
// in cell.h @protocol MyCellProtocol - (IBAction)doSomething:(id)sender; @end
add a delegate of type identifier (this means that it can be any object if it conforms to the protocol. In other words: this will be your collectionView, but you do not need to reference it
// in cell.h @property (assign) id<MyCellProtocol> cellDelegate;
Now you can call the delegate in your cell:
// in cell.m, some method: [self.cellDelegate doSomething:nil];
finally you need to install a delegate. When you create / customize your cell in the UICollectionViewController, set the controller as a delegate:
// in collectionViewController.m - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { UICollectionViewCell *cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"myCell" forIndexPath:indexPath]; cell.cellDelegate = (id<MyCellProtocol>)self;
auco
source share