Translating Objective-C adopts-protocol idioms to

Sometimes when looking at Objective-C samples, you mightrun into code that adopts protocols and you wonder how to portthat code to C#. It typically looks like this:

@interface TransparentOverlay : UIView <UITableViewDelegate, UITableViewDataSource>{}

The above means that the “TransparentOverlay” objectsubclasses UIView and adopts two protocols:UITableViewDataSource and UITableViewDelegate.

The above does not really work with MonoMac or MonoTouch,since we mapped protocols into classes. In both bindingsUITableViewDelegate and UITableViewDataSourceare “model”classes.

The real meat of this is that somewhere in theimplementation of TransparentOverlay, a UITableView will becreated, and both its delegate and its data source will beconfigured to point to the TransparentOverlay source,something like this:

- (void) setup{myTableView = [[UITableView alloc] initWithFrame:...];myTableView.delegate = self;myTableView.dataSource = self;}

The adopted protocol allows you to perform the assignemntthere.

The equivalent code in C# needs to create a helper classthat derives from the model. This is the full implementation:

class TransparentOverlay : UIView {    UITableView tableview;    class MySources : UITableViewSource {        TrasparentOverlay container;        public MySources (TrasparentOverlay container)        {            this.container = container;        }override void MethodOne (){            container.DoSomething ();}    }    void Setup ()    {        tableview = new UITableView (....);        var mySource = new MySources (this);        tableView.Delegate = mySource;        tableView.DataSource = mySource;    }}

Note that the UITableViewSource is an aggregated version ofUITableViewDataSource and UITableViewDelegate, it is just aconvenience Model for a very common idiom.

As you can see, instead of using “self” to point to the”TransparentOverlay” instance, you need to make it point tothe mySource instance.

The methods in MySource can get access to the content oftheir container by using the “container” property asillustrated by the MethodOne method.

Translating Objective-C adopts-protocol idioms to

相关文章:

你感兴趣的文章:

标签云: