Reputation: 2565
I'm just copying codes from an old project. I found something strange and I don't know how to do that. I just want to create that "Chart View Model" like below images. I also need an outlet too.
There is also a corresponding class.
class ChartModel: NSObject {
// .....
}
All I want to know is the purpose of using model in storyboads and how to do that.
Upvotes: 1
Views: 39
Reputation: 534893
Have you ever put a gesture recognizer into a storyboard scene? This is exactly parallel. The loading of the nib instantiates the gesture recognizer and attaches it to a view, so that you don't have to do that in code. That's what's happening here.
Any NSObject subclass can be instantiated as a nib object. Find the Object in the library:
Drag it from the library right into the scene; select it and change its class in the Identity inspector to the desired class (ChartModel).
Now you face the problem of what will happen to this instance when it is created at nib-loading time. On iOS, it will vanish in a puff of smoke unless someone else retains it. The usual solution is that you've got some other nib object with an outlet to this Object. Now, when the nib loads, the Object is instantiated and assigned to the corresponding property in the other nib object. That is what your outlet does:
@IBOutlet var chartViewModel : ChartModel!
Okay, but so far, that is exactly equivalent to saying
var chartViewModel = ChartModel()
It's just that, instead of instantiating the ChartModel in code, we instantiate it by the loading of the nib.
So why do that in the first place? Why instantiate this ChartModel from the nib instead of in code? It makes sense only if a ChartModel itself has outlets that can be configured in the nib. You didn't show us that (you only showed the first line of the declaration of class ChartModel
) so it's impossible to say more about what the actual purpose was in this case.
Upvotes: 1