Accessing the model

Conceptually, a TTilesView knows its associated TTilesModel and has access to it. But what actually happens is that the TTilesView gets a TModelReference and uses that reference to gain temporary access to the model. The view's access to the model should only be temporary, because a model can be shared by several views and modified by other objects.

The Compound Document framework provides an easy way for you to ensure the model is properly locked and unlocked. You can use the template class TModelPointerTo<AModel> to create a smart pointer to a model. A smart pointer locks and unlocks the target object automatically when you instantiate and destroy the smart pointer object. By creating a const TModelPointerTo<AModel>, you get read-only access to the model--to get write access, create a non-const pointer. You instantiate this class with a TModelReference, and you get an object that acts just like a pointer to a TModel.

For example, the TTilesView DrawContents function uses this class to handle locking the model, as follows:

  1. TModelPointerTo<AModel> is instantiated with a TModelReference to the associated TTilesModel. DrawContents creates a const pointer because it needs only read-access to the model (it doesn't modify the data--it only displays it). TTilesView gets the correct TModelReference using the TGUIBundle mechanism--see "Using GUI bundles" on page 18.
  2. The TModelPointerTo<TTilesModel> locks the model corresponding to the TModelReference you pass in.
  3. The TModelPointerTo<TTilesModel> uses the TModelReference to look up the model and get a pointer to it.
  4. DrawContents uses the pointer to read data from the model and display it.
  5. When the DrawContents function finishes executing, the lock on the model is released and the pointer is destroyed.
NOTE The lock is also automatically released if an exception occurs.

If you use TModelPointerTo<AModel> to access a model, you don't have to explicitly lock and unlock the model because the pointer object does it for you. However, you should keep in mind that a model must be locked before you can access it and unlocked when you're finished with it, so you must make sure you have a locking mechanism in place before accessing a model. If you don't lock a model before accessing it, your program will probably generate exceptions or freeze.

This diagram shows how the TTilesView DrawContents function uses TModelPointerTo<TTilesModel> to lock the model.



[Contents] [Previous] [Next]
Click the icon to mail questions or corrections about this material to Taligent personnel.
Copyright©1995 Taligent,Inc. All rights reserved.

Generated with WebMaker