Apple Mac cocoa entry-level tutorial-helloworld!

Source: Internet
Author: User

Cocoa tutorial 1-helloworld!
Source:
Www.cocoadev.cn


First, use xcode to create a new project. Here suppose you have installed the development tool. If not, you can use the Development CD or system CD installation, or register a free download in the http://connect.apple.com.

-Open xcode. The default installation path is/developer/applications/

-File menu: new project...

-Select the template "cocoa application. the two commonly used templates at the beginning are cocoa document-based application ". the latter applies to applications with multiple similar windows, such as text processors.

-Click "Next"

-Enter a project name (the default path is your user directory, which is OK). Enter "helloworld ".

-Click "finish ".

-Your project window appears.

-Now let's see what files are generated. in the left column, click the small arrows on the left of "classes", "Other sources", and "resources.
Classes should be empty now. you can create a new class file here. for large projects, more groups such as the three can be generated to facilitate management, but now this is fine.
Other sources contains the default "Main. m" file and another "helloworld_prefix.pch". In most cases, you do not need to modify these two files. "Main. m" contains the application entry.

Resources contains three files:
You can set the settings file, application name, version number, and Icon name of the info. plist application here. Now you can use the default settings.
Mainmenu. NiB is an interfacebuilder file used to store all interface projects.
Infoplist. Strings, a string containing information about the system. If it is opened, it will be clear at a glance.
There is also a small arrow on the left of the last two, because the corresponding localized files must be added to the two groups respectively.

-Now, compile and execute the command. You can click "Build and go" in the window or use the corresponding command in the build menu.

An empty window will pop up after a short period of time. Now exit the new Hello world application.

Use interface builder to define user interfaces

In this step, we use interface builder to slightly change the interface.

-Double-click mainmenu. nib in xcode. This will start interface builder and open the. NIB file.

-Check out this "mainmenu. NIB "window. this is the file you just opened. interface builder should also open two projects: "mainmenu" and an empty window (corresponding to mainmenu. window in NIB ).

-Change mainmenu. Click the first menu and change "newapplication" to "helloworld ".

You can change other menus, or delete some menus if needed, because they are not used in this tutorial, but there is no harm, so keep them there.

-Click window and add something to it. If it is not on the desktop, double-click "window" in "mainmenu. Nib" to make it appear.

In the "Tools" menu, select "attributes inspector" to create a new panel called "window attributes ".

-Change the title of window to "Hello world". Edit it in the "title" column of "window attributes.

-Adjust the size of the window to make it smaller.

-Remove the left check box of resize in "window attributes", so that the user of the program cannot change the window size.

-Click a library panel opened at the beginning of interface builder, open cocoa, and select view & cells.

-Scroll the bar to the right to display "label", drag it to the window, and double-click this label to modify its text content.

-If you are interested, you can add other things in the window.

-You can use the "command-R" shortcut to view the interface effect immediately.

-Enter "command-Q" to exit the test mode.

-Store this change and exit interface builder.

Back in xcode (back to xcode)

-Now click "build and run". You can see the changes in mainmenu and the content in the window.

-If you exit xcode, the compiled program can be found in the build directory of the project directory.
Is that all?

Yes, this is the case for this tutorial. Of course, this tutorial does not show much, but I hope to help you see that using Apple's tools and cocoa can easily create really good user interfaces.

You can familiarize yourself with the various controls that can be used on the user interface. Although you do not know how to use them for the moment, they will be exposed in the future.

In the next tutorial, we will add the objective-C code and introduce outlets and actions.

Cocoa tutorial 2-outlets and actions

The first step is to connect

-First, use xcode to generate a new project named atomicity.

-Double-click "mainmenu. Nib" in the project to start interface builder.

-Drag the following control from the library panel to the window, which is a slide and a text edit box.

-If you save and run the application now, you will find that the two parts are working, but you certainly want to do more than that, for example, display the value of the slider in the text box.

To do this, press Ctrl and hold the slider, drag the mouse to the text box, and open the mouse. A connection menu will appear on the screen.

-In "received actions", select takeintvaluefrom. This indicates that the text box obtains an integer from the slider, that is, the position of the pointer.

-Save and test this application. Now the text box displays the value of the pointer position of the slide bar.

One control part

-Now, add the following two parts, one button and one label in the window:

-What I want to do here is to make the following labels show whether the pointer of the slide bar is on the left or right. To do this, some code must be added (Haha, I have to move my hand at last ).

-Create a control "controller" object. as its name says, This controller is used to control what happens in the window. if you want to know more details, Apple's document is a good reading material. Read the section about MVC (model/View/controller) and (model/View/controller. this tutorial does not care about this.

Open cocoa in the library panel and select objects & controllers. drag a "nsobject" to mainmenu. in the nib window. this is the root object. Our controller object only needs to inherit some general properties from it.

Select Identity inspector from the tool menu, and enter "electricitycontroller" in the class column in the displayed identity panel"

-Add two outlets and one action. outlets allows you to access other components in your code. It is equivalent to a pointer type parameter that passes data in function programming. actions is a function activated by an event (such as clicking a button.

-Add the following outlets and actions:

-Then, compile the corresponding code. because the synchronization between xcode and interface builder is not very good in this regard, our method is to first go to xcode, select the new file in the File menu, then select the objective-C class in cocoa in the window, and enter "electricitycontroller. M "is the file name of the newly created class. Click Finish to finish. Two new code files are added to the class group of the project. return to interface builder and click mainmenu. in nib, select write class file in the File menu. In the displayed window, the default path should be the path of the project. If not, select back. then click Save to save. the following will prompt you whether to merge or replace, and select replace.

-Now return to xcode and double-click to open the two newly added files. You will see the following code already in it.

Copy content to clipboard

Code:

#import <Cocoa/Cocoa.h>

@interface ElectricityController : NSObject {
    IBOutlet id textZone;
    IBOutlet id topSlider;
}
- (IBAction)whereButtonAction:(id)sender;
@end
Copy content to clipboard

Code:

#import "ElectricityController.h"

@implementation ElectricityController
- (IBAction)whereButtonAction:(id)sender {
   
}
@end

The first is the header file, which contains the definition of this class, and the second contains the code to implement this class, which is basically empty now.

-Now return to interface builder for necessary connection. Remember to press Ctrl and then left click and drag the mouse to connect?

From electricitycontroller to the slider: select the outlet topslider.

From electricitycontroller to the bottom text Tag: select the outlet textzone.

From the button to policicitycontroller: Select wherebuttonaction in received actions.

Let's modify the code.

-Click the File menu in interface builder and select Save to save. Return to xcode to modify electricitycontroller. M and double-click it.

-We need to modify the event that occurs when the button is clicked. This will use the previously created action.

Replace-wherebuttonaction with the following code:

Copy content to clipboard

Code:

        - (IBAction)whereButtonAction:(id)sender {
            if ([topSlider intValue]<50)
                [textZone setStringValue:@"Cold"];
            else
                [textZone setStringValue:@"Hot"];        
        }

If you do not have one, it's time to get to know the objective-C language. For example, go to the Apple website to read related documents.

So what is the code?

Copy content to clipboard

Code:

if ([topSlider intValue]<50)

The first line is to ask the value of the slider and compare it with 50.

Copy content to clipboard

Code:

[textZone setStringValue:@"Cold"];

If the value is less than 50, set the content of the text label to cold. @ "cold" to represent a String constant of the nsstring type.

Copy content to clipboard

Code:

            else
                [textZone setStringValue:@"Hot"];

Otherwise, do the same thing, but display "hot ".

Try your application!

-Click build and run to test your code!

New project

Create a new project first:

Start xcode
File menu: new project
In the dialog box, select "cocoa application"
Click Next
Project name: popreferences
Click Finish

Now set a preference preset file:

Click the arrow on the left of the targets group.
Double-click popreferences
Click propertities
In the identifier column, enter "org. projectomega. popreferences ", or other. the preset settings of the application will be stored in a plist file named this. The default path of this file is ~ /Library/preferences/

Here, we use Java-type rules to name this preference preset file, which is also recommended by Apple (to some extent, the URL address is written in turn ). one major benefit of doing so is that preference files will be put together by production companies.

Use interface builder to design

Now let's design the dialog box to be used in this tutorial.

Expand the "Resources" group in xcode
Double-click mainmenu. nib to start interface builder to open it.
Change your window as shown below. this includes the controls used by most preferences. the radio control has two options by default. You can change the number in the cells column of attributes inspector. in addition, the attributes inspector of each radios item must be configured with the following tags: 0, 1, 2, 3, corresponding to Radio 1, Radio 2, Radio 3, Radio 4, it will be used later. to select a single radio item, you may need to click the corresponding item several times until the item is highlighted.

Create outlets/actions

Now you need to generate a controller object for this dialog box and add outlets/actions. Use the same method in the previous tutorial.

Click library panel
Drag an nsobject to the mainmenu. Nib window.
Name the class as "prefcontroller" on the identity panel"
Add five outlets (one for each control) and two actions, and name them as follows:

Now, create the prefcontroller class:
Like in the previous tutorial, go back to xcode,
File menu, new file, select objective-C class, name it prefcontroller. M, finish, generate prefcontroller. h and prefcontroller. M.
Return to interface builder, confirm to select prefcontroller in mainmenu. Nib, and then
File menu, write class file, select the path of the project (if the default value is not), and replace.
The two new files in xcode should be:

Copy content to clipboard

Code:

#import <Cocoa/Cocoa.h>

@interface PrefController : NSObject {
    IBOutlet id PrefEdit;
    IBOutlet id PrefPopup;
    IBOutlet id PrefRadios;
    IBOutlet id PrefSlider;
    IBOutlet id PrefSwitch;
}
- (IBAction)PrefRestoreAction:(id)sender;
- (IBAction)PrefSaveAction:(id)sender;
@end
Copy the content to the clipboard code:#import "PrefController.h"

@implementation PrefController
- (IBAction)PrefRestoreAction:(id)sender {
   
}

- (IBAction)PrefSaveAction:(id)sender {
   
}
@end
Connect outlets/actions

Return to interface builder to connect actions and outlets to different parts, or use Ctrl + mouse to drag.
From the "Restore" button to "prefcontroller" in mainmenu, select prefrestoreaction in receive actions.

Similarly, connect the "save" button to the "prefcontroller" prefsaveaction
Connect outlets from the prefcontroller to the corresponding component. The connection Inspector panel should be shown as follows:

Finally, connect to "prefcontroller" from "file's owner" and select the delegate. in this way, the prefcontroller will be notified about the application's initial and closed information, so that we can use the corresponding delegate method to process the information, for example, the read and storage of the preset values of this project are suitable for processing at these times.

Header file

Save and exit interface builder, and return to xcode to add code!
It is a good habit to refine the iboutlet type ID to a specific type, so change the "prefcontroller. H" file to the following:

Copy content to clipboard

Code:

#import <Cocoa/Cocoa.h>

@interface PrefController : NSObject
{
    IBOutlet NSTextField*   PrefEdit;
    IBOutlet NSPopUpButton* PrefPopup;
    IBOutlet NSMatrix*      PrefRadios;
    IBOutlet NSSlider*      PrefSlider;
    IBOutlet NSButton*      PrefSwitch;
}
- (IBAction)PrefRestoreAction:(id)sender;
- (IBAction)PrefSaveAction:(id)sender;
@end

Real code

Edit "prefcontroller. m" now. The next section will explain the details.

Copy content to clipboard

Code:

#import "PrefController.h"

@implementation PrefController

-(Void)Applicationdidfinishlaunching:( Nsnotification *) Notification
{
// Automatically store the window location
[[Prefedit window] setframeautosavename: @ "prefwindow"];

// Automatically restore the preset value
[Self prefrestoreaction: Self];
}

-(Ibaction) prefrestoreaction :( ID) sender
{
// Read preference preset files
Nsuserdefaults * defaults = [nsuserdefaults standarduserdefaults];


// Text box
// Obtain the preference preset value or set the default value
Nsstring * mystr = [defaults stringforkey: @ "editfield"];
// If the preset value or the default value does not exist, generate
If (mystr = nil)
Mystr = @ "empty ";
// Apply the value to the Dialog
[Prefedit setstringvalue: mystr];

// Pop-up menu
// Obtain the preference preset value or set the default value
Int Pos = [defaults integerforkey: @ "popup"];
// If the preset value or the default value does not exist, 0 is returned and can be used as the default value.
// Apply this value to the dialog box
[Prefpopup selectitematindex: POS];

// Radio button
Int posradios = [defaults integerforkey: @ "radios"];
[Prefradios selectcellwithtag: posradios];

// Slide bar
Int slider = [defaults integerforkey: @ "Slider"];
[Prefslider setintvalue: slider];

// Switch button
Int myvalue = [defaults integerforkey: @ "Switch"];
[Prefswitch setintvalue: myvalue];
}

-(Ibaction) prefsaveaction :( ID) sender
{
// Read preference preset files
Nsuserdefaults * defaults = [nsuserdefaults standarduserdefaults];

// Text box
// Obtain text from the text box
Nsstring * mystr = [prefedit stringvalue];
// Store this text object
[Defaults setobject: mystr forkey: @ "editfield"];

// Pop-up menu
// Obtain the option value
Int Pos = [prefpopup indexofselecteditem];
// Store this value
[Defaults setinteger: POS forkey: @ "popup"];

// Radio button
Int posradios = [prefradios selectedrow];
[Defaults setinteger: posradios forkey: @ "radios"];

// Slide bar
Int slider = [prefslider intvalue];
[Defaults setinteger: slider forkey: @ "Slider"];

// Switch button
Int myvalue = [prefswitch intvalue];
[Defaults setinteger: myvalue forkey: @ "Switch"];
}

@end

Application startup

Copy content to clipboard

Code:

-(Void)Applicationdidfinishlaunching:( Nsnotification *) Notification
{
// Automatically store the window location
[[Prefedit window] setframeautosavename: @ "prefwindow"];

// Automatically restore the preset value
[Self prefrestoreaction: Self];

// Display window
[[Prefedit window] makekeyandorderfront: Nil];
}

Signal "-Applicationdidfinishlaunching"The prefcontroller will receive the issue when the application is started. This is a good place to restore the preference preset value. The following line does this:

Copy content to clipboard

Code:

        [self PrefRestoreAction:self];

-This is also a good place to store the window location. You do not need to write several lines of code to implement this. The cocoa framework provides a command with only one line of code to complete this task: "-setframeautosavename"

Copy the content to the clipboard code:        [[PrefEdit window] setFrameAutosaveName:@"PrefWindow"];Store preference preset values

-First, you need to read the default file. Its name is determined at the beginning:

Copy content to clipboard

Code:

        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

-Obtain the corresponding value from the control (or an existing variable)
-Store these values to the default file. Here, for example, store the preference "myvalue" to the key "Switch.

Copy content to clipboard

Code:

        [defaults setInteger:myvalue forKey:@"Switch"];

Restore preference preset values

-First, you need to read the default file.

Copy content to clipboard

Code:

        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

-Next, the following line extracts the value "popup" in preference. if this item does not exist in the default file, the returned value is 0, which can be accepted as the original default value. if it is a string, the return value is "nil" if the corresponding key does not exist ".

Copy content to clipboard

Code:

        int pos = [defaults integerForKey:@"Popup"];

-Finally, the restored values can be restored to the corresponding control.

Verify your application

If everything is okay, you will get a result.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.