How to bind data in View - ios

Actually someone asked me this question and I'm also interested to know, that how to bind data to a UI element directly. I know UITableview have Datasource property but it doesn't bind data directly. We have to use its protocol methods to bind data in code.
Is there any other way from which we can bind data to the View or is this possible or not? In .Net gridview we can bind data from database to gridview directly.

Update: If you mean synchronizing backing data with UI elements then read the last paragraph.
It would be against the recommended MVC pattern to bind data directly to the view if I understand your question correctly. Check the below links for more info.
Why MVC?
[Why MVC instead of good old ASP.NET? Still not grasping why I should go this route?][2]
However if you do want to bind data directly, there is nothing stopping you from it, even though it might be a bad idea unless the use case is trivial. For e.g. UITableViews are available with static cells. And if a pre-built UI element doesn't have a provision to bind data (don't know of any) to it directly, you could make a similar UI element that serves the purpose.
However it would take way more effort to build such and element than to supply data to it the existing one through preferred methods.
By binding data directly, if you mean supplying the data through interface builder, then you are out of luck. In Cocoa (for OS X application development), there is something called Bindings that help you synchronize your UI elements with the backing data. However in iOS there isn't such a thing. But you could use Key - Value - Observing to achieve this to some extent.
Also why iOS might not have such bindings may be partially answered here:
Is there any technical/conceptual reason why iOS does not support Cocoa Bindings?.
And check this if you have a need on such functionality: Is there any data binding mechanism available for iOS?

While it isn't exactly binding, I have used didSet property observers to update UI elements like this:
var label: UILabel?
var labelText = "Change me." {
didSet {
label?.text = labelText
}
}
That assumes you have initialized label somewhere appropriately. I believe that is the closest you can get in iOS.

Related

iOS: When to use delegate/dataSource (protocols) vs. properties

Many CocoaPod and native iOS libraries use protocols that they name either CustomClassDelegate or CustomClassDataSource as a means to do some setup or customization. I was wondering when I should use this programming model, because it seems like I could accomplish much of this with properties.
Example
If I define a custom class called SmurfViewController that has a SmurfLabel, is it better practice to store the smurfLabel as a private property and have a public computed property called smurf that looks like this:
private var smurfLabel = UILabel()
public var smurf: String {
get {
return smurfLabel.text
}
set(text) {
smurfLabel.text = text
}
}
or should I define a SmurfDataSource that has a public function that looks like this:
func textForSmurfLabel() -> String {
return "smurfText"
}
When should I use what here?
You should just use a property for that. Delegates and Datasources are for different controllers/Objects to speak to one another when the alternative is to instantiate the controller/object from the navigationStack/view hierarchy. A Delegate forms a specific communication between the two that allows for clear knowledge in what their relationship is while keeping them decoupled (assuming you try to keep it that way). I disagree with the article that says callbacks are "better". They are amazing and I advise using them often, but just understand that most options that swift provides you with have a place where they work best.
I might be slightly bias, but Swift is an amazing language with OOP being a backbone and everything it has was well put together in order to provide the correct tools for each situation you find yourself in.
I often find myself using both of those tools and one other more customizable option in my more advanced setups where I have an overseeing viewController that manages many child controllers. It has direct access to all of them that are active but if any of its children communicate with it, it is through delegates. Its main job is just to handle their place on the screen though, so I keep everything manageable.
Delegates and data sources are more appropriate for offloading behaviors to other entities, not simple values. In other words, if your type just needs a value for something, you are correct that it makes more sense to expose that as a property that can be set from the client code.
But what should happen (for example) when a user taps a specific table view cell is a behavior that shouldn't be hard coded into UITableView. Instead, for flexibility, any implementation of that behavior can be created in a delegate and called by the UITableView when appropriate.
In general, think of delegation as a way to make subclassing unnecessary, because the methods you would normally override in a subclass are instead moved into a protocol that can be implemented by ANY type, not just a subclass of the base type. And instead of calling internally implemented methods to get certain behaviors, your type is simply calling those behaviors on an external collaborating class (the delegate).
So perhaps the best guideline for when to use a data source or delegate is the question: "Would I need to subclass this class in order to change this value or behavior in the future". If the answer is no, because you can just set a property from client code, then don't use delegation. If the answer is yes, then offload that behavior to a delegate or data source instead of forcing future programmers to subclass your class to make it work for their use case.
Delegate is an interface for the undefined activities.
so when you make a SDK or framework, you must provide an interface so that users can write a proper code for the interfaces' expecting activity.
i.e, Table View needs a datasource to show it's contents, but the apple's library developers doesn't know the content whatever contents their library users will use. so they provided an interface like datasource, delegate.
and in the library, they just call this methods. that's the way the library should be made.
But in your code, the label is defined very explicitly as well as it's in the current view, and you don't need to make an interface for an undefined activity.
if you want know more about this kind of coding style, you need to do some researches on Software Design Pattern.
https://en.wikipedia.org/wiki/Observer_pattern
https://en.wikipedia.org/wiki/Delegation_pattern
https://en.wikipedia.org/wiki/Software_design_pattern
I love apple's sdk very much, because they used all the needed design patterns very properly.

Using BIND framework for two way data-binding in iOS

I'm trying to use BIND framework to bind a UITableView with UITextfield's which can edit the content.
I'm trying to achieve something very similar to how binding is done in Mac OSX. Bind a datasource with view, let the user make changes, on save the data is saved after validations.
Typically this is done by subscribing the delegate or observing the valueChanged event from textfield. I wanted to try out a new way to reduce this, that's how I came across BIND framework.
It encourages to use an MVVM framework, usually seen in .NET. Binding is as simple as mapping the keypath of model with the view component. But I'm finding it difficult to achieve to two way binding, from model to component and back.
BINDINGS(MHPersonNameViewModel,
BINDViewModel(name, ~>, textLabel.text),
BINDViewModel(ID, ~>, detailTextLabel.text),
nil);
Could anyone point me in the right direction.
This is a late answer, and not even really an answer to your question, but I hope it's still useful.
Take a look at https://github.com/mutech/aka-ios-beacon. This is a binding framework that integrates into Interface Builder and (by default) uses the view controller as root view model.
You don't have to write any code to initialize bindings. In your example, assuming that the view controller has (KVO compliant) properties "name" and "ID", you would just need to set the UILabel "text binding" properties to name and ID (you find the in the property panel in interface builder and enable bindings for the view controller (also in the properties panel).
And that should be all you have to do to establish bindings.
In versions up to 0.1.1 of AKABeacon, "enable bindings" is not yet there. In this case your view controller would have to inherit from AKAFormViewController.

Binding imperatively

Is there a way to set up bindings imperatively. An example use case:
var el2 = new MyElement();
el2.myProp = this.$.anotherElement.anotherProp
That won't setup a binding, it just assigns the value or object. I'd like to find a way to do something like:
el2.myProp.bindTo(this.$.anotherElement.anotherProp)
Possible?
Polymer 1.0 does not support this at the moment - as explained by #kevinpschaaf in Github https://github.com/Polymer/polymer/issues/1778.
(comment by #kevinpschaaf)
No, we don't currently support this, outside of dom-bind, which is the
only template implementation that late-binds instance children. You
can document.createElement('template', 'dom-bind'), then you can
dynamically append children with binding annotations to its content,
and the bindings will only be evaluated once the dom-bind is attached
to the document. See tests here that show this usage of it:
https://github.com/Polymer/polymer/blob/master/test/unit/dom-bind.html#L95
Note that dom-bind does not currently allow binding to outer scope, so
it has limited use in custom element templates (it's main use case is
for binding between elements in the main document), and that's not
likely to change short-term.
We are achieving a lot of performance optimization by baking the
binding connections into the prototype at registration time for an
element (rather than at instance time), and we haven't built up enough
of the machinery to easily allow runtime addition/removal of bindings.

How to get all allocated instances of specific class in Objective C?

I am trying to implement component for possibility to apply different skins to views and controllers at runtime without reinitialising these controls. I want to use such logic:
Declare protocol with methods for applying skins.
All necessary classes implements this protocol.
When user selects skin all instances of classes that conform to protocol receive message to apply skin.
So I know how to get all necessary classes that conform to my specific protocol by using objc_getClassList and class_conformsToProtocol functions.
But how to get all allocated instances of these classes for sending message to them?
I know that it could be implemented by internal logic of every class by storing all instances in static storage and returning array by class method. But it isn't elegant solution. I'm finding more universal solution where I can add new skinnable controls in easy way.
It sounds very much like you're reinventing <UIAppearance>. You should at least start there. It's what it's for. Also see Peter Steinberger's writeup for discussion of adding custom properties.
To your basic question, there is not a runtime call to enumerate all allocated objects of a class. It would add a lot of overhead to provide that (objects come and go all the time and very quickly). Even if you could do it, you probably shouldn't. But since you're talking about visible views, then you can always do this by enumerating the view hierarchy under NSWindow. Any views not currently in the view hierarchy should be expected to correctly redraw in an new style the next time they come on the screen.
But I'd start with <UIAppearance>.

Using element to element binding in Silverlight 3?

I don't really see the need for element to element binding in Silverlight 3 if using MVVM. Won't having one property directly affect another proper cause that property to be untestable?
To me, it makes more sense to do a two way binding to a explicit property defined in the ViewModel.
I agree that the use of MVVM severely deflates the usefulness of element to element binding.
Still, if all you are doing is binding two elements using a ViewModel property... what can you test? You can test that setting a property in the ViewModel sends a PropertyChanged event... but thats about it. Only when something else cares about that value is it useful to test a property like that.
In the simple cases, I can see element2element binding being more efficient and less code.

Resources