0

I'm trying to understand the usage of protocol and delegates in Swift and their equivalence in c# for Xamarin.iOS.

Microsoft has a decent documentation about that here but for me it lacks the swift or objectiveC counterpart of c# code to allow me to understand what to do.

I'm in the process of porting an existing Swift gist to c# Xamarin iOS.

I have this protocol:

protocol GridLayoutDelegate: class {
    func scaleForItem(inCollectionView collectionView: UICollectionView, withLayout layout: UICollectionViewLayout, atIndexPath indexPath: IndexPath) -> UInt
    func itemFlexibleDimension(inCollectionView collectionView: UICollectionView, withLayout layout: UICollectionViewLayout, fixedDimension: CGFloat) -> CGFloat
    func headerFlexibleDimension(inCollectionView collectionView: UICollectionView, withLayout layout: UICollectionViewLayout, fixedDimension: CGFloat) -> CGFloat
}

That I have converted to:

public interface IGridLayoutDelegate
{
    uint ScaleForItem(UICollectionView collectionView, UICollectionViewLayout layout, NSIndexPath indexPath);
    nfloat ItemFlexibleDimension(UICollectionView collectionView, UICollectionViewLayout layout, nfloat fixedDimension);
    nfloat HeaderFlexibleDimension(UICollectionView collectionView, UICollectionViewLayout layout, nfloat fixedDimension);
} 

So far so good.

Later in the code I have this (for now) strange declaration:

weak var delegate: GridLayoutDelegate?

What concerns me is that it is never assigned later in the swift code.

For now I have my c# class declared as:

public class GridLayout : UICollectionViewLayout, IGridLayoutDelegate
{
...
}

What would be the corresponding code in c#?

1 Answers1

0

Swift language uses Automatic Reference Counting, so it needs weak var to deal with memory leaks, caused by circular references.

As opposing, C# uses Garbage Collector, which handles circular references by itself without extra manual effort (more detailed here: Garbage collector and circular reference . This works when both objects in the circular reference have similar lifetime, if one of the objects outlives another without unsubscribing there might pop up Lapsed listener problem)

So I think in C# you just need:

public class GridLayout : UICollectionViewLayout, IGridLayoutDelegate
{
    private IGridLayoutDelegate @delegate;

I'm not familiar with Xamarin, so I cannot say for sure how @delegate should be initialized.

Renat
  • 7,718
  • 2
  • 20
  • 34