Translate

Mostrando entradas con la etiqueta XCode. Mostrar todas las entradas
Mostrando entradas con la etiqueta XCode. Mostrar todas las entradas

martes, 5 de marzo de 2013

IOS Popup Messages



You can create popup messages showing a title, a message, an a set of buttons. In my example the button "Clear Data" call this popup message to confirm the action. These are the steps needed to create the popup message:

1. Add to the interface of your header file.

2. Create the alert message with the following code:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"WARNING"
                                                                     message:@"All data wil be erased. Are you sure?"
                                                                     cancelButtonTiltle:@"Cancel",
                                                                     otherButtonTitles:@"Ok", nil ];
[alert show]
[alert release]  ------> if you have ARC enabled don´t use this line.


3. And finally you must use the following method  to control which button was pressed, and its associated action.


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex







martes, 12 de febrero de 2013

Hidding a numeric keyboard in IOS

With the standart keyboard we have a "Done" button, so once the user click over this "Done" button the action "Did en on exit" is called. Then we can use the following piece of code to close the keyboard just when the users touch over this "Done" button:

       [self.theEditOutlet resignFirstResponder ]

But with the other numerical types of keyboardas this button doesn´t exist. In this case we could add a toollbar including a custom "Done" button, or more easilly using the method "touchesBegan".

This method must be implemented in the .m ViewController file and must be as follows:

-(void) touchesBegan:(NSSet  *)touches withEvent:(UIEvent *)event
{
    [self.theEditOutlet resignFirstresponder ]
}

miércoles, 6 de febrero de 2013

windows are expected to have a root view controller at the end of application launch

windows are expected to have a root view controller at the end of application launch

This is a warning that the compiler shows, so the application works. It is caused  because you have added a subview to a view without declaring the root View Controller first. To fix it you must replace:

[windows addSubview:self.aViewController.view];

for:

[windows setRootViewController:self.aViewController];

martes, 27 de marzo de 2012

Cambios del Data Model/ How to manage changes in the data model


Usually when you are creating you application you need to make a few changes to your data model. If you change the data model and try to run your application you would have a problem with the persistent store, because the file containing the data  does not match to the actual model data.
One way to solve this problem is to find the file in where the data are stored, and delete it. The problem is that you are going to loose the data stored on it.
The other way to solve it is to use model versioning, which is a feature provided by XCode to maintenance changes in our model data.

Model versioning allows us to made changes to the data model, and also migrate the data from old version to new version.

There are to types of migration, depending on the types of changes you made to your data model. These are automatic or lightweight migration and manual migration.

Here we are going to see how to made a lightweight migration for a small change in our model. In this case we need to add a new Attribute for an Entity.

1º Select the actual model data before you make any change on it. Choose Editor menu, and Add Model Version… then you must give a name for the new model version, and choose the model version from we are going to derive the  new model.



Then a new model data is created, and take notice that this new model is exactly to the one we have choose to derive from. In this new model we could made the changes we need. In this case add a new attribute.


2º Once we have created the new attribute, we need to generate the files .h and .m for the Entity changed.  Be careful to choose the new data model, click over the modified Entity, and then choose Editor on the menu, and Create NSManagedObject SubClass. Then a new version of the .h and .m will be created but with the same name as the old one, so a warning message about to replace the files will appear.



3º Now we are going to add new code for the place in where the persistent store coordinator is created:

NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                  [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];


The file must appear as follows:



This peace of code indicates that the migration process is going to be automatically.

4º Finally we are going to set our  new data model as de active one. In this case you must click over the root of the data model, and in the File inspector in the right panel go to Versioned Core Data Model, and choose the appropriate one.




And that´s all, you can run your application, but previously I recommend you to Clean and to Build it.





jueves, 1 de marzo de 2012

Cerrando una aplicación de manera correcta / The right way to Close an App


Para hacer que una aplicación cierre correctamente al cerrar la última ventana añadiremos el siguiente método en el fichero .m del Aplication Delegate

To make an application close when the last windows were closed you must add the following method in the .m Apllication Delegate´s file


- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender
{
      return YES;
}

lunes, 27 de febrero de 2012

Custom Sheets


En un post anterior veíamos como mostrar mensajes de alert mediante la clase NSAlert. (http://ugeblog.blogspot.com/2012/02/xcode-mensajes-de-aviso.html).
En estos mensajes de alerta podemos mostrar alguna advertencia y pedir confirmación mediante botones, pero en determinados casos podemos querer usar el panel para pedir algún dato adicional al usuario de manera que no se pueda acceder al resto de la aplicación mientras el panel esté desplegado (comportamiento modal). Para ello contamos con el uso de los customs sheets.

In a post before we could see how to show alert messages using the class NSAlert. (http://ugeblog.blogspot.com/2012/02/xcode-mensajes-de-aviso.html).
With those messages we could show any kind of alert requesting a user confirmation using diferentes buttons, but in some cases we need something more like a simple confirmation, for example we could need the user enter some kind of data forbiding the access to the rest of the application until the user complete entering the data required (modal behaviour). For this purpose we have the Custom Sheets.

El ejemplo que vamos a hacer será muy simple y constará de dos ventanas, una principal con un botón que al pulsarlo nos muestra un panel asociado a esta ventana. Este segundo panel se ocultará mediante un botón.

The example application we are going to made is very simple. It wil have two windows, one main window with one button which opens another secondary window.   This secondary Windows opens from the first one so we can´t do anything in the application without clossing the last window opened.



En los ejemplos de Apple e incluso en la documentación de cómo manejar Custom Sheets se nos dice que para ello implementemos el panel en su propio fichero .nib y que llamemos a su creación desde el código, pero…¿porque complicarnos la vida pudiéndolo hacer simple?. La idea que proponen es crear un fichero .nib (o .xib) para cada ventana, crear un controlador para cada ventana, realizar las correspondientes declaraciones de cada clase de manera que cada una conozca a la otra y una vez así hacer la llamada al panel desde la ventana principal. Un poco liante… yo prefiero hacerlo fácil, y para ello lo mejor es definir el panel dentro del fichero nib de la propia ventana que necesita mostrar el panel.

In the Apple example and also in the documentation which explain the uses of customs sheets, we could see they uses an independent .nib file for define the second panel, but… why not made it easy?, in my opinion is more easy and clear to implementate the second panel in the same .nib file the main window has. The other way is to create a .nib file for each window/panel, and of course his own class controller. Also you would need to declare each class inside the other, on the way any window could “see” the others windows it must use. To much complicated, too many files, declarations, and so on,…a prefer to simplify it.

Comenzaremos creando por lo tanto un aplicación con una única ventana de entrada que llamaremos Main Window.  A esta ventana le añadiremos un botón que posteriormente nos servirá para mostrar el panel.

El siguiente paso es crear el panel, y para ello en el Object Library buscaremos un objeto del tipo panel o del tipo HUD Window y lo arrastramos sobre el fichero .xib que posee la ventana. Igualmente le ponemos un botón que luego servirá para ocultar el panel,. Por ultimo y para evitar que se muestre el panel al iniciar desmarcaremos la casilla Visible at Launch. Debería quedar de la siguiente manera:

We will start creating a new Project with one main window, with one button used to opening the panel. Also we must créate the panel, and for this, we need to search into the Object Library for a Panel, o for a HUD Window, drag inside the nib file near the main window. Also we need another button inside the panel to close it. Is important to unmark the Visible At Launch option of the panel to avoid the panel to be shown at the startup of the application.



Una vez creadas la ventana principal y el panel crearemos unOutlet del panel y dos action, uno desde cada botón llamados mostratPanel y cerrarPanel. Tanto el Outlet del panel como los Action se crearan en el fichero AppDelegate de la ventana principal, donde encontraremos un Outlet a la ventana principal. El fichero AppDelegate.h debería quedar algo así:

Once we have created both the window and the panel, we must créate one Outlet for the panel and to Actions, one for the button in the main window, and another for the button in the panel. This Outlet and Actions must be created into the AppDelegate.h file wich control the main Window. This AppDelegate.h file must appears as follows:



Finalmente implementaremos el código que sirve para mostrar y cerrar el panel en el fichero Appdelegate.m, el cual debería quedar de la siguiente manera:

Finally we must type the code to show and to closet the panel. Both methods must be implementated into the AppDelegate.m file inside the Actions we defined previously. It must appears as follows:



Y eso es todo, seguimos aprendiendo …
And this is it,…. keep going in the XCode/Cocoa learning…


viernes, 10 de febrero de 2012

XCode: Más Ventanas / More Windows


Con este ejemplo vamos a ver la forma en que trabajar con varias ventanas en nuestra aplicación usando un xib/nib para cada ventana. Para ello tendremos una ventana inicial que incluirá un botón que abrirá una segunda ventana.

Whit this example we are going to see the way to work with different windows in our application, using one xib/nib for each window. The example application would have a main window with one button. This button will open a second window.

Creamos un proyecto que llamaremos “twoWindows”. En la ventana principalal añadiremos un botón que llamaremos “Abrir Segunda Ventana”.
De este botón crearemos un Action arrastrando con ctrl pulsado desde el botón mencionado hasta el fichero AppDelegate.h, llamando a dicha Action “mostrarSegunda”, después implementaremos el código necesario para esta Action.
Una vez creado el proyecto tendremos creada una primera ventana que se almacena en un archivo tipo xib llamado MainMenu.xib. iIgualmente incorporará una clase llamada AppDelegate.

First we must create a new project called "twoWindows". In the main window we must add one button with the title "Abrir Segunda Ventana".
From this button we will make an action control dragging to the AppDelegate.h file. The name for this action would be "mostrarSegunda". Later we will implement the code for this action.
Once we have created the project we will have a a first window associated to a xib file called MainMenu.xib. Also we have an asociated class called AppDelegate. 



Vamos a crear ahora la segunda ventana, para ello primero crearemos el fichero xib donde se define la ventana. En la barra lateral izquierda (Navigator), seleccionamos el Project Navigator y a su vez hacemos click sobre la carpeta del proyecto. Después hacemos click con el derecho y del menú que sale seleccionamos la opción New File.

Now we are going to make the second window. First we need a xib file where the window is defined, so in the left side bar (Navigator) we must choose the Project Navigator and click over the project folder. Then we must make a right click and choose New File in the menu that appears.



En la ventana que se abre escogeremos MacOS / User Interface y Window, y pulsaremos sobre Next, pondremos como nombre “SecondWindow” y por último pulsaremos sobre Create

In this window we must choose MacOS / User Interface and Window, Next and set the name for the new window as "secondWindow". Finally we click over Create.



Se crea entonces la segunda ventana. Crearemos ahora una clase que nos permita controlar dicha ventana. Para ello volvemos al Navigator y dentro de este al Project Navigator, volvemos a hacer botón derecho sobre la carpeta del proyecto y escogemos de nuevo New File.
Una vez en este menú escogemos la opción MacOS / Cocoa /Objective-C Class y pulsamos sobre Next.



Nos aparecerá otra ventana donde además de poner el nombre, “SecondWindowController”, escogeremos la clase a la que pertenece, en este caso NSWindowController



Pulsamos sobre Next, y sobre créate y se creará la clase, quedando el proyecto de la siguiente manera:



El siguiente paso será unir la nueva ventana con su controlador creado. Para ello en el Project Navigator hacemos click sobre SecondWindow.Xib y una vez se muestre este en el Interface Builder, haremos click sobre el File´s Owner, el cubo transparente. En la barra lateral (Utilities) escojeremos el identity Inspector (tercer botón por la izqda.), y donde pone Class, borraremos la que hay por defecto y escribiremos el nombre de la nueva clase que hemos creado: SecondWindowController.



Por último desde el File´s Owner y con ctrl pulsado arrastraremos hasta el window, y crearemos un outlet sobre window tal y como se muestra a continuación:

Drag files


Declaramos la nueva clase creada para la segunda ventana en el fichero AppDelegate.h que controla la primera. Añadimos esto:



El siguiente paso será añadir la declaración de SecondViewController.h en el fichero AppDelegate.m, así como escribir el código asociado al botón que abrirá la ventana.



Y listo, de esta manera se abre la segunda ventana desde la primera.


domingo, 5 de febrero de 2012

XCode: Mensajes de aviso / Alert Messages

El manejo de mensajes de aviso se puede hacer a través de los objetos NSAlert, los cuales nos permiten crear mensajes de avisos con diferentes botones y que a su vez estos botones puedan realizar una acción determinada.
En el ejemplo de hoy vamos a hacer un botón que cierre nuestra aplicación. Una vez pulsado el botón se mostrará un mensaje solicitando la confirmación de cerrar o no la aplicación.

This time we are going to see how to display alert messages in our application. For this purpose we have the class NSAlert. With this class we could create alert messages using buttons, message text, icons as we need.
The example application we are going to create shows a button in the centre of the windows, once this button is pressed a message appear asking you if you really want to close the application.




Crearemos un proyecto vacío (ponle el nombre que te de la gana, es lo de menos). No hace falta Core Data ni nada mas, será un ejemplo muy simple.
Colocaremos un botón en el centro de la ventana principal y le pondremos de título "Cerrar". Después crearemos un Action asociado a este botón sobre el fichero AppDelegate.h. Puedes llamar a esa Action como "cerrarAplicacion"


Start creating an empty project, (you can name as you want, it does´t matter). Also we do not need Core Data, or anything more, it´s going to be a very simple application.
Once you have created the empty application go to your main window and place a button in the center of it. Then create an Action from this bottom to the AppDelegate.h. "cerrarAplicacion" could by the name for the action. 

La implementación de dicho botón consistirá primero en crear un objeto del tipo NSAlert, después lo configuraremos con los diferentes botones, y textos que necesitemos mostrar. Y por último haremos una llamada a mostrar el mensaje de alerta creado, indicando sobre que ventana mostrado, y a que método llamar cuando se pulse alguno de los botones.
El método se llamará "alertDidEnd", y en el implementaremos lo que necesitamos que se haga al pulsar el botón correspondiente. En nuestro caso será cerrar el programa, lo que se hará simplemente usando la función exit(0).

The implementation for this action will consist first on create an NSAlert object, and then populate this object with a pair of buttons, "Si, sierra" and "No en ningún caso", the texts wich explain the alert, and also the type of alert. Finally we show the alert, setting from which window appears (_window), the behavior of the alert, in this case, modal behavior, and the selector called when the user press one of the buttons in the alert message.
This selector calls a method called "alertDidEnd". It´s implements the action to close the application in  case the user press the first button defined. Using exit(0) you can close the application.




viernes, 3 de febrero de 2012

XCode: Cocoa Bindings


Bindings es una tecnología en Cocoa que nos permite sincronizar objetos. Es una herramienta que facilita la comunicación entre objetos y supone una adaptación de la metdología MVC (Model-View-Controller). Básicamente permite realizar una conexión entre el atributo de un Object view (un objeto usado para mostrar valores), y un objeto usado para almacenar ese valor.
Por ejemplo, supongamos un campo Edit y una variable temperatura. Podremos hacer un binding entre ellos de manera que si cambio el valor de la variable se cambiará automáticamente el contenido del campo Edit, y viceversa.

Vamos a realizar un ejemplo donde tendremos un slider horizontal sincronizado con un campo de edición, de manera que si muevo el slider, se actualizará el edit, y si escribo un valor en este último se actualizará la posición del slider.

Creamos un proyecto que llamaremos binding.



Iremos a la ventana y colocaremos dos componentes, un NSEdit y un NSSlider como se muestra en la imagen siguiente:



La forma de realizar esto usando el tradicional MVC sería usando outlets y action, esto es, para cada componente creamos un outlet que los referencie, y después un action que se asigne a ambos componentes.
Dicho action detecta cual de los dos componentes es el sender, para primero leer el valor del componente y después actualizar dicho valor en el otro componente.


Esto supone tener que escribir algo de código, que para un ejemplo simple como este no supone mayor problema, pero si necesitásemos conectar objetos más complicados como tablas de datos que necesitan actualizar a su vez otras tablas, o componentes la cosa se complica. Para eso emplearemos la tecnología Binding.

Lo primero sería crear una clase que defina al objeto que mantendrá el valor. Crearemos la clase “Valor”.





Dentro de esta implementaremos un objeto que simplemente tendrá un atributo que se llamará “miValor” de tipo double.

Una vez creado vamos al Interface Builder y añadiremos un NSObject que vincularemos a esta clase recién creada.





Añadimos ahora un Object Controller que vincularemos al objeto de la clase creado anteriormente, y además añadiremos un Key que referencie al atributo miValor de la clase Valor.




Por último nos queda por establecer los bindings entre el atributo miValor de la clase Valor y los dos componentes, de manera que se mantengan sincronizados, es decir, que cambiado uno de ellos afecte automáticamente  al otro.

Para ello seleccionamos el primer componente, la barra y vamos al binding inspector. Expandimos la opción Value y la configuramos como se muestra:




Repetimos la misma acción para configurar el binding del campo edit.




Y ejecutamos el programa. En este punto cualquier cambio en cada uno de los componentes afecta al otro, es decir si muevo la barra se mostrará el valor en el campo edit, y si en este pongo un número entre 0 y 100 la barra se colocará en esa posición.

Esta es la forma en la que el uso de Bindings nos permite reducir la cantidad de código a escribir, facilitándonos la programación.