Model-View-Controller implementation help

Hello, all. I'm updating an old, clunky, slow-as-molasses application to a slightly more responsive and expandable app with the help of the MVC pattern. However, I'm having a little trouble figuring out the best way to implement MVC in a Java app. Specifically, I'm not sure of the best way to get the model and two views talking to each other.
My model comes in the form of a couple manager classes that provide access to all the business data for the application. This is a relatively simple client-server app where the server can request that certain data be added or deleted, and the model responds accordingly. Similarly, scheduled tasks that run every 2 minutes can cause certain data to expire or become scheduled for display.
The model provides addXXXChangeListener methods. When a model change occurs that listeners need to know about, the model calls a notifyListeners method, and all registered listeners are notified of the change. View classes that are interested in hearing about model changes register themselves as listeners with the model and implement methods in the XXXChangeListener interface. In this way, the interaction between the model and view is almost exactly like existing interactions between event sources and listeners in Swing/AWT.
Right now, there isn't a lot of decoupling between the model and view, since the View obviously needs a reference to the model to add itself as a listener. The controller for the app sets all that up. Is this a viable way of implementing MVC in a Java app? Any suggestions or advice would be greatly appreciated.

Right now, there isn't a lot of decoupling between
the model and view, since the View obviously needs a
reference to the model to add itself as a listener.
The controller for the app sets all that up. Is
s this a viable way of implementing MVC in a Java
app? Any suggestions or advice would be greatly
appreciated.In classic MVC, the code that registers the listeners, captures the events and updates the model should be in the controller. The advantage being that you could theoretically change the view to use a different model. In reality, the view is generally (but not always) pretty specific to the model (while pieces of the model may not be) so there is little gained by doing this. The other advantage is that this can be a little cleaner and allow the controller to be 'smarter'.
If you are simply worried about coupling the vew to a specfic implementation of the model, create interfaces for the Model classes and let the Controller supply the View with references to the implmentations.

Similar Messages

  • Real Model View Controller with JTextField

    Hi!
    I am new to Java (so please bear with me). I am building a swing application. I already have added a JTable with a corresponding table model that extends AbstractTableModel. Rather than store the data in the table model, I have modified setValueAt and getValueAt to write and read cell data to another location. So far, everything is fine. When doing setValueAt, I have a fireTableCellUpdated statement that I use to update the edited cell. So far, things are all still fine.
    I would like to do the same thing with a JTextField. I found an example in Core Java Volume 1 for create a class that extends PlainDocument. It uses insertString to update the document in a way that ensures that only numbers are entered. I implemented this. Everything is still fine. I changed insertString to update my remote repository (a field in another class). Everything is still fine. Next, I tried to change (override) both getText methods to read from the repository. This works, but is not reflected on the screen.
    I realize that I need the equivalent of a fireTableCellUpdated statement for the class that extends PlainDocument, but do not know how to do this.
    I have looked a lot over the internet for the model view controller implementation. I know that it can be done using event and event listeners, but this seems to defeat the purpose of the model view controller - it seems like you ought to be able to directly modify the model object to access external data.
    My code is below.
    Thanks/Phil Troy
    * PlainDocument class to make it possible to:
    * - Make sure input in unsigned integer
    * - Automatically save data to appropriate locate
    * This will hopefully eventually work by overriding the insertString and getText methods
    * and creating methods that can be overridden to get and save the numerical value
    class UnsignedIntegerDocument extends PlainDocument
         TutorSchedulerPlusSettings settings;
         JTextField textField;
         public UnsignedIntegerDocument(TutorSchedulerPlusSettings settings)
         {     super();
              this.settings = settings;
         public void setTextField(JTextField textField)
         {     this.textField = textField;
         // Overridden method
         public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
         {     if (str == null) return;
              String oldString = getText(0, getLength());
              String newString = oldString.substring(0, offs) + str +oldString.substring(offs);
              try
              {     setValue(Integer.parseInt(newString));
                   super.insertString(offs, str, a);
                   fireInsertUpdate(new DefaultDocumentEvent(offs, 10, DocumentEvent.EventType.INSERT));
              catch(NumberFormatException e)
         public String getText()
         {     return String.valueOf(getValue());
         public String getText(int offset, int length) throws BadLocationException
         {     String s = String.valueOf(getValue());
              if (length > 0)
                   s = s.substring(offset, length);
              return s;
         public void getText(int offset, int length, Segment txt) throws BadLocationException
         {     //super.getText(offset, length, txt);
              char[] c = new char[10];
              String s = String.valueOf(getValue());
              s.getChars(offset, length, c, 0);
              txt = new Segment(c, 0, length);
         public String getValue()
         {     int i = settings.maxStudents;
              String s = String.valueOf(i);
              return s;          
         void setValue(int i)
         {     settings.maxStudents = i;
    }

    Hi!
    Thanks for your response. Unfortunately, based on your response, I guess that I must not have clearly communicated what I am trying to do.
    I am using both JTables and JTextFields, and would like to use them both in the same way.
    When using JTable, I extend an AbstractTableModel so that it refers to another data source (in a separate class), rather than one inside of the AbstractTableModel. Thus the getValueAt method, getColumnCount method, setValueAt method, . .. all call methods in another class. The details of that other class are irrelevant, but they could be accessing data from a database (via JDBC) or from other machines via some other communication mechanism.
    I would like to do exactly the same thing with a JTextField. I wish for the data to come from a class other than an object of type PlainDocument, or of any class that implements the Document interface. Instead, I would like to use a class that implements the Document interface to call my external class using methods similar to those found in AbstractTableModel.
    You may ask why I would like to to this. I have specific reasons here, but more generally this would be helpful when saving or retrieving parameters set and displayed in a JTextField to a database, or when sharing JTextField to multiple users located on different machines.
    As to whether this is real MVC or not, I think it is but it really doesn't matter.
    I know that I can accomplish what I want for the JTextField using listeners. However, I would like my code for the JTables to be similarly structured to that of the JTextField.
    Thanks/Phil Troy

  • Update methode in model-view-controller-pattern doesn't work!

    I'm writing a program in Java which contains several classes. It must be possible to produce an array random which contains Human-objects and the Humans all have a date. In the program it must be possible to set the length of the array (the number of humans to be produced) and the age of the humans. In Dutch you can see this where is written: Aantal mensen (amount of humans) and 'Maximum leeftijd' (Maximum age). Here you can find an image of the graphical user interface: http://1.bp.blogspot.com/_-b63cYMGvdM/SUb2Y62xRWI/AAAAAAAAB1A/05RLjfzUMXI/s1600-h/straightselectiondemo.JPG
    The problem I get is that use the model-view-controller-pattern. So I have a model which contains several methodes and this is written in a class which inherits form Observable. One methode is observed and this method is called 'produceerRandomArray()' (This means: produce random array). This method contains the following code:
    public void produceerMensArray() throws NegativeValueException{
         this.modelmens = Mens.getRandomMensen(this.getAantalMensen(), this.getOuderdom());
    for (int i = 0; i < this.modelmens.length; i++) {
              System.out.println(this.modelmens.toString());
    this.setChanged();
    this.notifyObservers();
    Notice the methods setChanged() and notifyObservers. In the MVC-patterns, these methods are used because they keep an eye on what's happening in this class. If this method is called, the Observers will notice it.
    So I have a button with the text 'Genereer' as you can see on the image. If you click on the button it should generate at random an array. I wrote a controller with the following code:
    package kristofvanhooymissen.sorteren;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    /**Klasse GenereerListener.
    * @author Kristof Van Hooymissen
    public class GenereerController implements ActionListener {
         protected StraightSelectionModel model;
         /**Constructor.
         *@param model Een instantie van het model wordt aan de constructor meegegeven.
         public GenereerController(StraightSelectionModel model) {
              this.model = model;
         /**Methode uit de interface ActionListener.
         * Bevat code om de toepassing te sluiten.
         public void actionPerformed(ActionEvent arg0) {
         this.model=new StraightSelectionModel();
         try{
         this.model.produceerMensArray();
         } catch (NegativeValueException e){
              System.out.println("U gaf een negatieve waarde in!");
         this.model.setAantalMensen((Integer)NumberSpinnerPanel.mensen.getValue());
         this.model.setOuderdom((Integer)NumberSpinnerPanel.leeftijd.getValue());
    StraighSelectionModel is of course my model class. Nevermind the methods setAantalMensen and setOuderdom. They are used to set the length of the array of human-objects and their age.
    Okay. If I click the button my observers will notice it because of the setChanged and notifyObservers-methods. An update-methode in a class which implements Observer.
    This method contains the follow code:
    public void update(Observable arg0,Object arg1){
              System.out.println("Update-methode");
              Mens[] temp=this.model.getMensArray();
              for (int i = 0; i < temp.length; i++) {
                   OnbehandeldeLijst.setTextArea(temp[i].toString()+"\n");
    This method should get the method out of the model-class, because the produceerRandomArray()-methode which has been called by clicking on the button will save the produce array in the model-class. The method getMensArray will put it back here in the object named temp which is an array of Mens-objects (Human-objects). Then aftwards the array should be put in the textarea of the unsorted list as you could see left on the screen on the image.
    Notice that in the beginning of this method there is a System.out.println-command to print to the screen as a test that the update-method has been called.
    The problem is that this update method won't work. My Observable class should notice that something happened with the setChanged() and notifyObservers()-methods, and after this the update class in the classes which implement Observer should me executed. But nothing happenens. My controllers works, the method in the model (produceerRandomArray() -- produce random array) has been executed, but my update-method won't work.
    Does anyone has an explanation for this? I have to get this done for my exam an the 5th of january, so everything that could help me would be nice.
    Thanks a lot,
    Kristo

    This was driving me nuts, I put in a larger SSD today going from a 120GB to a 240GB and blew away my Windows Partition to make the process easier to expand OS X, etc.  After installing windows again the only thing in device manager that wouldn't load was the Bluetooh USB Host Controller.  Tried every package in Bootcamp for version 4.0.4033 and 5.0.5033 and no luck.
    Finally came across this site:
    http://ron.dotsch.org/2011/11/how-to-get-bluetooth-to-work-in-parallels-windows- 7-64-bit-and-os-x-10-7-lion/
    1) Basically Right click the Device in Device manager, Go to Properties, Select Details tab, Choose Hardware ids from Property Drop down.   Copy the shortest Value, his was USB\VID_05AC&PID_8218 
    2) Find your bootcamp drivers and under bootcamp/drivers/apple/x64 copy AppleBluetoothInstaller64 to a folder on your desktop and unzip it.  I use winrar to Extract to the same folder.
    3) Find the files that got extracted/unzipped and open the file with notepad called AppleBT64.inf
    4) Look for the following lines:
    ; for Windows 7 only
    [Apple.NTamd64.6.1]
    ; No action
    ; OS will load in-box driver.
    Get rid of the last two lines the following:
    ; No action
    ; OS will load in-box driver.
    And add this line, paste your numbers in you got earlier for USB\VID_05ac&PID_8218:
    Apple Built-in Bluetooth=AppleBt, USB\VID_05ac&PID_8218
    So in the end it should look like the following:
    ; for Windows 7 only
    [Apple.NTamd64.6.1]
    Apple Built-in Bluetooth=AppleBt, USB\VID_05ac&PID_8218
    5) Save the changes
    6) Select Update the driver for the Bluetooth device in device manager and point it to the folder with the extracted/unzipped files and it should install the Bluetooth drivers then.
    Updated:
    Just found this link as well that does the same thing:
    http://kb.parallels.com/en/113274

  • WebCenter Sites and Model–view–controller (MVC) framework

    A customer of our started developing their sites using Webcenter Sites, they want to support additional functionality such as transaction management, exception handling, custom logging and so on. I was wondering if anyone has experience with the Model–view–controller (MVC) framework, they consider it an ideal candidate for these features. Has anyone here used the MVC framework in conjunction with WebCenter Sites to write additional java classes, facade layers and utilize the Spring controller to wire the same ? Are you aware of any other options available for this purpose ?
    regards,
    Pietro

    Hi Pietro -
    Using Sites IN a MVC framework is very difficult, because the entire context of WebCenter Sites is burned into the COM.FutureTense.Servlet.SContentServer servlet.  You can't really work around that with any degree of reliability.  Unfortunately, that means that dropping Sites into a pre-existing third party MVC framework doesn't really work. 
    There are a lot of good reasons for that, not the least of which is the two-tiered pagelet-level caching system that makes Sites so very fast at delivery... not that it's any consolation.
    To deal with this some former colleagues of mine and I built the GST Site Foundation ("GSF") framework, which provides a Spring-like MVC container WITHIN sites, instead of the other way around.  If you're familiar with Spring, you'll see patterns similar with the GSF.  My current team and I have blogged about this extensively:
    What is this whole GST Site Foundation thing? | Function1
    Create a Simple "Contact Us" Form with GSF | Function1
    How to Add Your Own DAO to the GSF Actions | Function1
    The full stream is here:  GSF | Function1
    But ultimately, the special sauce is the following: in Sites, create an XML element that contains nothing but a <FTCS> tag, a <CALLJAVA> tag, and a closing </FTCS> tag.  Your CALLJAVA will then call a class that implements the Seed or Seed2 interface, and from in there you have access to the (properly managed) ICS object where you can do all of your magic.  You can then build a lightweight controller here to handle any action you can dream up:
    https://github.com/dolfdijkstra/gst-foundation/blob/master/gsf-wra/src/main/java/com/fatwire/gst/foundation/controller/A…
    Let me know if I can help!
    Regards,
    Tony

  • Model View Controller design question

    Hi,
    I am creating a brand new web application, and would like to use the Model View Controller design (using Beans, JSP, and Servlets).
    I am looking design suggestions for handling page forwarding. I don't want to post to a jsp, and I don't want to hard code the name of the next jsp on the forward or in the servlet. I was thinking of having a properties or xml file, which lays out the routing read by the servlet and then dispatched.
    Does anyone have any other design suggestions on the best way to handle routing someone through a web application?

    What you can do is create a servlet that initializes the mappings on startup...create a hashtable of mappings from a file. You'll have to parse the file, so you can either use XML and use a SAX parser, or your own format (name=path? ie. order=/order.jsp), which ever one is simpler for you to use.
    To load the servlet on startup, you specify the load-on-startup parameter in the web descriptor, web.xml:
    <servlet>
         <servlet-name>MappingsLoader</servlet-name>
         <servlet-class>packagename.MappingsLoader</servlet-class>
         <load-on-startup>1</load-on-startup>
    </servlet>
    where load-on-startup number is the order in which it loads the servlet, 1 being first.
    Then once you've created the hashtable, store it in servlet context.
    When you want to forward something, just use a requestdispatcher object and the hashresult to forward the request to another web component (in this case, a jsp).

  • How to add the model view controller in webcenter portal framework application

    i create a webcenter portal framework application.how to create a model class in my application..please help me.

    What you mean by this. You mean having model layer in webcenter portal framework application? Whats the exact requirement.? You want to create ADF BC in portal app.
    If you want to use adf taskflow application , i will recommend you to make separate adf application and use as shared lib in portal.

  • Model View Controller Deployment

    Hi,
    I have tried to deploy the ViewController layer in an OC4J instance, and the model and another instance of OC4J.
    When I tried to execute the page in the ViewController layer I receive the following message. It seems like I need something to configure in order that my databindings could access to the model layer. I have already changed the Databindings.cpx in which I point the remote Configuration of the AppModule.
    Does somebody know what is wrong or how I can solve the problem?
    500 Internal Server Error
    JBO-30003: The application pool (ec.com.carrasco.accionespersonal.model.AppModule9iAS) failed to checkout an application module due to the following exception:
    oracle.jbo.JboException: JBO-29000: Unexpected exception caught: oracle.jbo.JboException, msg=JBO-29000: Unexpected exception caught: oracle.jbo.JboException, msg=JBO-25222: Unable to create application module.
    at oracle.jbo.common.ampool.ApplicationPoolImpl.doCheckout(ApplicationPoolImpl.java:1743)
    ## Detail 0 ##
    oracle.jbo.JboException: JBO-29000: Unexpected exception caught: oracle.jbo.JboException, msg=JBO-25222: Unable to create application module.
    ## Detail 0 ##
    oracle.jbo.JboException: JBO-25222: Unable to create application module.
    at oracle.jbo.common.ampool.DefaultConnectionStrategy.createApplicationModule(DefaultConnectionStrategy.java:156)
    ## Detail 0 ##
    javax.naming.NamingException: Error instantiating web-app JNDI-context: No location specified and no suitable instance of the type 'ec.com.carrasco.accionespersonal.model.common.ejb.beanmanaged.RemoteAppModule' found for the ejb-ref ejb/AppModuleBean

    thank you for your reply,
    i did as you said but the problem persists,
    actually my Model Project contains a Session Bean , and the web browser error says that it can't find this session bean.
    this is the first time i deploy an application using jdeveloper 10g, Do you think that i have to create a Deplyment Descriptor or something like that?
    Message was edited by:
    rsader

  • Model-View-Presenter - help

    Hi,
    I recently read about Model-View-Presenter on Martin Fowler's website, and elsewhere. I think I understand the idea...
    The view just displays the GUI components..events fired from the View are delegated to a Presenter. The presenter then deals with the model and updates the View accordingly. Sound about right?
    Ok, so I learn best by example..and I haven't found any code samples yet, so I thought I'd give it a shot. Below is my code...
    Model
    * the model to be displayed in a View
    public class Album {
         private boolean isClassical;
         private String composer;
         public String getComposer() {
              return composer;
         public void setComposer(String composer) {
              this.composer = composer;
         public boolean isClassical() {
              return isClassical;
         public void setClassical(boolean isClassical) {
              this.isClassical = isClassical;
    View - interface
    import java.awt.event.ActionListener;
    * An interface which defines the methods needed by a presenter
    public interface View {
         public boolean isClassical();
         public void setClassical(boolean b);
         public boolean isComposerEnabled();
         public void setComposerEnabled(boolean b);
         public void addClassicalChangeListener(ActionListener al);
         public void showView();
    View - implementation
    import java.awt.Dimension;
    import java.awt.event.ActionListener;
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    * A an implementation of the View interface.  It shows a checkbox
    * and a textfield.
    public class MyView extends JFrame implements View {
         private JCheckBox checkboxClassical;
         private JTextField textfieldComposer;
         private MyPresenter mp;
         public MyView() {
              checkboxClassical = new JCheckBox("Classical");
              textfieldComposer = new JTextField();
              textfieldComposer.setPreferredSize(new Dimension(100, 20));
              textfieldComposer.setEnabled(false);
              JPanel p = new JPanel();
              p.add(checkboxClassical);
              p.add(textfieldComposer);
              add(p);
              setSize(600, 400);
         public void addClassicalChangeListener(ActionListener al) {
              checkboxClassical.addActionListener(al);
         public void setPresenter(MyPresenter mp) {
              this.mp = mp;
         public void setClassical(boolean b) {
              checkboxClassical.setSelected(b);
         public boolean isClassical() {
              return checkboxClassical.isSelected();
         public void setComposerEnabled(boolean b) {
              textfieldComposer.setEnabled(b);
         public boolean isComposerEnabled() {
              return textfieldComposer.isEnabled();
         public void showView() {
              setVisible(true);
    Presenter
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    * A presenter for a View.  When the "classical" fires
    * an ActionEvent, the "composer" component is enabled or disabled.
    public class MyPresenter {
         private Album album;
         private View view;
         public MyPresenter(Album album, View viewVal) {
              this.album = album;
              this.view = viewVal;
              view.addClassicalChangeListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        view.setClassical(view.isClassical());
                        view.setComposerEnabled(view.isClassical());
              view.showView();
    }and here is a simple Main to tie it togehter.
    * Ties together the M-V-P
    public class Main {
         public static void main(String[] args) {
              Album al = new Album();
              al.setClassical(false);
              MyView myView = new MyView();
              MyPresenter mp = new MyPresenter(al, myView);
              myView.setPresenter(mp);
    }Ok, the idea is this. The GUI shows a checkbox and a textfield. basically, if the checkbox is selected the textfield is enabled and can be typed into. If the checkbox is not selected, the textfield is disabled. From the model point of view, if isClassical is false, then no composer can be defined.
    So, is my code following the pattern? Does anyone have any simple code to contribute as an example? For some reason is just seems weird to me that I would have an interface define a bunch of methods that the Presenter can call. And I have to create the Model and View which get passed to the presenter, and then I have to set the presenter on the view....it just seems weird to me.
    Any comments, suggestions, examples??
    Thanks for your time and contributions.

    The other information didnt answer my questions. The response was mixing the idea of MVC instead of MVP, and then the response discussed what they thought was wrong with MVP and why they use a different model. I am looking for help on understanding the pattern more, also for someoen (who knows about MVP) to look at my sample code and help me understand what I did right/wrong.
    Thanks.

  • Model View Control help!

    Hi!
    I have a var in Model called "age". From ActionPerformed in Control I want to take the value from a JTextField in View and update age. How do I do this?
    ActionPerformed is triggered by a JButton..
    Thx!

    With MVC you should create the model, view and controller in a driver class that creates all the compoents of the MVC and merges them together. You should be passing the model as a parm to the view in the constructor.
    Example Driver Class:
    public MVCDriverClass {
    // constructor and any other methods needed
    public void initialize() {
        MyModelInterface model = new MyModel();
        MyViewInterface view = new MyView();
        MyControllerInterface controller = new MyController(mode, view);
        model.initialize();
        view.initialize();
        view.showView();
    }Now in your model you need to make sure you are using the Observer pattern to notify all observers of any changes to the data model. Java already implements this for you if you want to use its utils. You simply need to extend the Observable class on your model to make it the subject and implement the Observer interface on each view you want the Subject (Observer) to notify of changes. You will see that the Observer interface has a method named update(Observer o, Object arg). You simply place any code in here that you need to update your UI values with. Let me know if you need any examples.

  • NSTimer - Model or View Controller

    Hi,
         i have a doubt on correct usage of NSTimer in a MVC pattern:
    let's suppose i'm building a chess game; a payer has 20 seconds to move one of his piece; a timer in view is present showing the time passing. If the time ends the player loose the time to move a piece.
    In this situation how to deal with NSTimer:
    I would like to put NSTimer in model since it seems to me it refers to game's logic. however doing this way my modell should know my controller in order to send recursively a message to update the "timer" (let's consider the time is a bart that becomes smaller with the time passing)
    Another solution is to put the NSTimer in view: i would then be able to update my "timeBar" and i would send recursively a message to my model asking: "is the time ended?". I do not like this solution since it seems to me the NSTimer is part of logic and i may thing the performance of the solution is not high.
    Could you please suggest me a correct approach?
    Kind Regards
    Nicolò

    You could argue that your timer is currently in a view controller, not a view. If the timer controls what the user is permitted to do in the view, it might not be appropriate to put it in the model.
    If you really want to put the timer in the model, the view controller could be a delegate of the model. The view controller would conform to the model's "timer" protocol by implementing delegate functions the model calls to notify the view controller of timer events.
    There are some scenarios where the model should contain information about the timer. For example, if a user quits the app in the middle of a turn, when the user restarts the app does he still have the remainder of the time to move? If so, the current time value (not the timer itself) should be part of the model so serializing/deserializing the model will include enough information to resume the game in the event iOS terminates the app.

  • How to import custom classes from model to view controller in adf?

    hi...
    i have some custom classes in model layer in adf.
    i want to use them in view controller but i cannot import them.
    how is this possible?
    my jdev version is 11.1.1.5

    You normally don't have to do anything special. The view controller project has a dependency to the model project. So simply typing the class name should show you hte option to generate the need import statement for the class.
    However, not all classes which reside in the model project should be imported into the view Controller as it might break the MVC pattern.
    Timo

  • How to implement navigation control inside view controller project

    Hi,
    I am trying to implement an navigation control in a view controller project.
    I am unable to do that process.
    Can anyone please suggest me how to do this navigation flow which should be placed inside view controller.
    SRI.

    Hi,
    I am using Jdeveloper 11.1.1.4.0.
    To use the appModules methods, I am creating the service interface and then I am creating the webservice proxy into another view controller project and access the appModule methods.
    Now, I don't want to create the webservice proxy. I want to directly access the appModule methods.
    Thanks,
    Rohit.

  • Call method with an argument from another view controller

    I have a UIViewController MainViewController that brings up a modal view that is of the class AddPlayerViewController. When the user clicks 'Save' in the modal view I need to pass the Player data (which is a Player class) from the modal view to the MainViewController in addition to triggering a method in the MainViewController. What's the best way to accomplish this? I'm new to cocoa and have only tried using delegates and some ugly hacks to no avail.
    Thanks for the help.

    If I understand correctly, you have:
    1. A model object, Player.
    2. A top view controller, MainViewController.
    3. Another view controller, AddPlayerViewController, which MainViewController displays modally.
    I'm guessing that AddPlayerViewController creates a new Player object and lets the user set its values, and you need a way to get that new Player into MainViewController once they're done.
    So, here's what I'd do:
    1. Create an AddPlayerViewControllerDelegate protocol. It should declare two methods, "- (void)addPlayerViewController:(AddPlayerViewContrller*)controller didAddPlayer:(Player*)newPlayer" and "- (void)addPlayerViewControllerNotAddingPlayer:(AddPlayerViewController*)controll er".
    2. Add an attribute of type "id <AddPlayerViewControllerDelegate>" called delegate to AddPlayerViewController. Also add a property with "@property (assign)" and "@synthesize".
    3. Modify AddPlayerViewController so that if you click the "Save" button, addPlayerViewController:didAddPlayer: gets called, passing "self" and the new Player object as the two arguments. Also arrange for clicking the "Cancel" button to call addPlayerViewControllerNotAddingPlayer:.
    4. Modify MainViewController to declare that it conforms to AddPlayerViewControllerDelegate. Implement those two methods (addPlayerViewControllerNotAddingPlayer: might be an empty method if you don't want to do anything).
    5. When you create your AddPlayerViewController, set its delegate to your MainViewController.
    If you need more detail, let me know what parts you need me to elaborate on.

  • Question about view/controller/nib class design

    Assume you need to make an application with, let's say, 15 different views in total. There are two extreme design choices you can use to implement the app:
    1) Every single view has its own view controller and a nib file. Thus you end up with 15 controller classes and 15 nib files (and possibly a bunch of view classes if any of your views needs to be somehow specialized).
    2) You have only one controller which manages all the views, and one nib file from which they are loaded.
    AFAIK Apple and many books recommend going purely with option #1. However, going with this often results in needless complexity, large amounts of classes (and nib files) to be managed and complicated class dependencies, especially if some of the views (and thus their controllers) interact with each other or share something (something which would be greatly simplified if all these related views were handled by one single controller class).
    Option #2 also usually ends up being very complex. The major problem is that the single controller will often end up being enormous, handling tons of different (and usually unrelated) things (which is just outright bad design). This is seldom a good design, unless your application consists of only a few views which are closely related to each other (and thus it makes sense for one single controller class to handle them).
    (Option #2 also breaks the strictest interpretation of the MVC pattern, but that's not really something I'm concerned about. I'm concerned about simple design, not about following a programming pattern to the letter.)
    A design somewhere in between the two extremes often seems to be the best approach. However, since I don't have decades of Cocoa programming experience, I would like to hear some opinions about this subject matter from people with more experience on that subject. (I do have object-oriented programming experience, but I have only relatively recently started programming for the iPhone and thus Cocoa and its design patterns are relatively new to me, so I'm still learning.)

    Somehow I get the feeling that my question was slightly misunderstood.
    I was not asking "which one of these two designs do you think is better, option #1 or option #2?" I already said in my original post that option #2 is bad design (unless your application consists of just one or two views). That's not the issue.
    The issue is that from my own experience trying to adhere very strictly to the "every single view must have its own view controller and nib file" often results in needless complexity. Of course this is not always the case, but sometimes you end up having controller classes which perform very similar, if not even the exact same actions, resulting in code repetition. (An OO'ish solution to this problem would be to have a common base class for these view controllers where the common functionality has been grouped, but this often just adds to the overall complexity of the class hierarchy rather than alleviating it.)
    As an example, let's assume that you have a set of help screens (for example one help screen for each major feature of the app) and a view where you can select which help view to show. Every one of these views has, for example, a button to immediately exit the help system. If you had one single controller class managing these views, this becomes simpler: The controller can switch between any of the views and the buttons of each view (most of them doing the same things) can call back actions on this controller (eg. to return to the help selection or to exit the help screen completely). These help screens don't necessarily have any functionality of their own, so it's questionable what do they would need view controllers of their own. These view controllers would basically be empty because there's nothing special for them to do.
    View controllers might make it easy to use the navigation controller class, but the navigation controller is suitable mainly for utility apps but often not for things like games. (And if you need animated transitions between views, that can be implemented using the UIView animation features.)
    I also have hard time seeing the advantages of adhering strictly to the MVC pattern. The MVC pattern is useful in things like web servers, where MVC adds flexibility. The controller acts as a mediator between the database and the user interface, and it does so in such an abstract way that either one can be easily changed (eg. the "view", which normally outputs HTML, could be easily changed to a different "view" which outputs a PDF or even plain text, all this without having to touch the controller or the model at all). However, I'm not seeing the advantages of the MVC pattern in an iPhone app. It provides a type of class design, but why is it better than some other class design? It's not like the input and output formats of the app need to be changed on the fly (which is one advantage of a well-designed program using the MVC pattern).

  • Passing field values from View Controller to Custom Controller

    Hi Experts,
    I am working on a customer requirment in which customer want to see the values of field from one view in another view. The Context node & Context node attribute are the same in both the views.
    I am aware that we need to pass the field values from view controller to custom controller in order to see the field in the subsequent view. I would like to kow how i can achieve that technically?
    Kindly let me your valueable suggesions.
    Best Regards,
    Prabahar

    Hi Carsten,
    Thank you for the detailed feedback.
    I want the fields ID_TYPE & ID_TYPE_DESCRIPTION from IUICMD/SearchAccount to be available in IUICMD/DetailAccount. I have created a context node u201CSEARCHu201D in view IUICMD/DetailAccount. I have created the context node with out choosing u201CCreate with Instanceu201D.  This Context node (SEARCH) is already available in IUICMD/SearchAccount as part of the standard.
    Below given is contents of the Method CREATE_SEARCH of my context class ZL_IUICMD_DETAILACCOUNT_CTXT of view IUICMD/DetailAccount, which is created by the Wizard during enhancement.
    method CREATE_SEARCH.
        DATA:
          model        TYPE REF TO if_bsp_model,
          coll_wrapper TYPE REF TO cl_bsp_wd_collection_wrapper,
          entity       TYPE REF TO cl_crm_bol_entity,    "#EC *
          entity_col   TYPE REF TO if_bol_entity_col.    "#EC *
        model = owner->create_model(
            class_name     = 'ZL_IUICMD_DETAILACCOUNT_CN00'
            model_id       = 'SEARCH' ). "#EC NOTEXT
        SEARCH ?= model.
        CLEAR model.
    bind to custom controller
      owner->do_context_node_binding(
               iv_controller_type = CL_BSP_WD_CONTROLLER=>CO_TYPE_CUSTOM
               iv_name = 'IUICMD/CuCoMD' "#EC NOTEXT
               iv_target_node_name = 'BUILHEADERSEARCH'
               iv_node_2_bind = SEARCH ).
    endmethod.
    I have enhanced the Custom Controller. Now it have new implementation class u201CZL_IUICMD_CUCOMD_IMPLu201D
    Let me know where I am doing mistake
    Thanks in advance
    Best Regards,
    Prabahar
    Edited by: Prabahar Raju on Sep 2, 2009 10:47 AM
    Edited by: Prabahar Raju on Sep 2, 2009 10:52 AM

Maybe you are looking for

  • How to get JToolBar location

    How can I find the current location of a JToolBar (NORTH, SOUTH, EAST, WEST or FLOATING) ? I've searched the forums for an answer to this question and seen the question asked before but no answer given. In short I have a situation where the contents

  • The install thing freezes!

    I tried a lot of times to install but it just doesn't work. (I also always tried to uninstalled it) What I do: 1. I go to the download page and press the yellow button 2. The other page loads 3. Internet Explorer asks if I want to install it and I pr

  • PE6 Burning RAW Photos???

    I am having a problem with burning my RAW (CR2) files on to a disk without them being converted to JPEG. I want to save them on a disk in RAW format so that I can get them off of my computer for space sake and still be able to edit them in RAW later.

  • Share screen connects, then disconnects

    I have a stumper. My screen share with my parents connects, then freezes and disconnects after 10 seconds of "innactivity" I can see the screen, so it doesn't seem likely it's a firewall issue. Thoughts?

  • Statistical Cost Elements

    Hello How can we create statsical cost elements for Incventory balance sheet items with 90 Category. Help wud be appreciated.