Objective-C basic tutorial-learning Summary

Source: Internet
Author: User

Outline:

Introduction

Notes compared with the C Language

Objective-C advanced features

Development Tool introduction (cocoa toolkit features, framework, source file organization; xcode usage Introduction)

Introduction:

1. Objective-C is an extension set of C language, which is mainly maintained by Apple and is the main development language in MAC systems.

In my opinion, objective-C is an alternative and non-mainstream language for people who are familiar with commonly used languages such as C and Java.

2. Develop Mac UIProgramThe cocoa framework is used. The components of cocoa include the foundation and application KIT framework.

[Foundation framework processes features under the user interface, such as data structures and communication mechanisms; application KIT framework includes advanced features of cocoa: user interface elements, printing, color, sound management, applescript, etc]

3. I learned this book:

I have mastered the syntax of Objective C and can understand what others have written.Code, You can also write code;

Familiar with the use of xcode in the development environment (including Project Creation, debugging, running, and code management)

And CNotes for Language Comparison:

1. File Introduction: Objective-C also uses header files with the suffix. h, but uses. m (that is, message, and other object-orientedProgramming LanguageIs also called method), as the suffix of the source file.

In objective-C, use # import <> instead of # include <>. # import ensures that the header file is only contained once.

2. Consistent with C:

Data Types, expressions, and various operators

Loop: For, while, do while, break, continue

Branch: If, else, switch

3. nslog () function: similar to printf (), You want to output information on the console. However, it adds some features, such as timestamps.

[Cocoa adds the NS prefix to all functions, constants, and type names .]

4. @ in front of double quotation marks indicates that the strings in double quotation marks should be processed as nsstring elements of cocoa.

5. boolean bool: Value: Yes, no;

6.% d indicates the output integer

% @ Indicates the output nsstring type

% S indicates the output String Array (char *);

7. square brackets in objective-C:

1. Used to notify an object of what to do.

2. The first item in square brackets is the object, and the rest is the operation you need to perform on the object.

3. In objective-C, an object is notified to execute an operation calledSend message. (Call method)

8. identifier ID: it is a generic type used to represent objects of any type.

9. Class declaration @ interface:

 

@ interface circle: nsobject // defines interfaces for the circle class; nsobject indicates the parent class.

{// The following are data members

shapecolor fillcolor;

shaperect bounds;

}

// method declaration

-(void) setfillcolor: (shapecolor) fillcolor; // The short line above indicates that this is a method declaration

// the short line is followed by the return type of the method

// followed by the method name

/ p>

// a parameter following the colon, (shapecolor) is the parameter type,

fillcolor is the parameter name

-(void) setbounds :( shaperect) bounds;

-(void) draw;

// minus sign is a normal function

plus sign is a static function

@ end // end statement

When objective-C sees the @ symbol, it is regarded as an extension of the C language.

The complete declaration of a class is as follows:

@ Interface cclassa (category): cbaseclass <Ia, Ib...>

// Class Name (category name): parent class <protocol>

10. Class implementation @ implementation

@ Implementation

@ Implementation circle

-(Void) setfillcolor: (shapecolor) c

{

Fillcolor = C;

}

-(Void) Draw

{

Nslog (@ "drawing a circle at (% d) in % @", bounds. x, bounds. y, bounds. width, bounds. height, colorname (fillname ));

}

@ End

The hidden object self corresponds to this in C.

Self-> fillcolor to access member variables.

11. Call the written classes and class functions:

// Create a new object and use the default initialization Function

Bank * bankdefault = [[Bank alloc] init];

// Call method:

[Bank addamount: 1];

[Bank print];

// Release the object:

[Bankdefault free];

12.

Two Parameter methods:

-(Void) settire: (tire *) tire // Declaration

Atindex: (INT) index;

// Use

[Car settire: Tire atindex: 2];

Objective-CAdvanced features:

1. Inheritance

Objective-C does not support multi-inheritance.

Super Keyword: Call the parent class of the class;

Superclass: another statement of the parent class. 

2.

Custom nslog () output:

You can add the description method to the class to customize how nslog () Outputs objects.

@ Implementation tire

-(Nsstring *) Description

{

Return (@ "I am a tire .");

}

Main ()

{

Nslog (@ "% @", tire [0]);

}

3.

Foundation kit:

Cocoa consists of two frameworks: Foundation kit [including some basic classes] And Application Kit. [including user interface objects and advanced classes]

Create a string:

Nsstring * test;

Test = [nsstring stringwithformat: @ "I'm % d years old! ", 23];

If the plus sign is added before the method when the method is declared, the method is defined as a class method. [This method belongs to a class object, not an Instance Object of the class .]

Nsarray class: it can store any type of objects.

It has two restrictions:

1. It can only store objective-C objects, but cannot store basic data types in C, such as int, float, Enum, and struct.

2. Nil cannot be stored (the zero or null value of the object). [because NIL is added at the end of the list to indicate that the list ends when nsarray is created .]

Create nsarray:

Nsarray * array;

Array = [nsarray arraywithobjects: @ "one", @ "two", nil];

Nsstring, nsmutablestring class;

[Nsstring is immutable, that is, once it is created, it cannot be changed by deleting a character or adding a character;

Nsmutablestring is variable.

These two classes are similar to the difference between the string and stringbuffer classes in Java .]

Nsarray, nsmutablearray class;

Nsenumerator enumeration;

Nsenumerator * emun;

Emun = [array objectenumerator];

Id thingie;

While (thingie = [enumerator nextobject]) {}

]

Nsdictionary: A Dictionary (a set of keywords and their definitions .) [Also becomes a hash, associated array], nsmutabledictionary class;

Nsnumber: Used to encapsulate basic data types, such as int, Char, float, and bool. [Package A basic data type into an object called packing .]

Nsvalue: It can wrap any class, And nsnumber is its subclass.

Nsnull:

When "CF" is displayed in cocoa, it indicates that it is related to Apple's core foundation framework.

Nsautoreleasepool: Automatically releases the memory pool.

 

4.

Memory Management

Each object has a reference count associated with it (also called a retention count)

When an object is created using the alloc, new, or copy message (a copy of the receiving object is generated), the reference count of the object is set to 1;

This value is added when a retain message is sent to an object;

This value is reduced when a release message is sent;

When the reference count of an object changes to 0, objective-C will automatically send a dealloc message to the object. Destroy the object.

You can override this method in your own object,

You can use the retaincount message to obtain the reference counter value.

-(ID) Retain;

-(Void) release;

-(Unsigned) retaincount;

Automatic release pool: autorelease pool;

Create:

NSAID utoreleasepool * pool;

Pool = [[NSAID utoreleasepool alloc] init];

Destruction:

[Pool release];

Note: xcode automatically generates code. When the pool is destroyed, [pool drain] is used. The drain method only clears the release pool, but does not destroy the pool. therefore, you still need to use release when writing your own code.

In addition, drain applies only to Mac OS 10.4 and later versions, while release applies to all versions.

This object is automatically released only when an autorelease message is sent to an object.

For example, [Car autorelease];

Gold guidelines for memory management: 

Only objects created using the alloc, new, and copy methods require the programmer to send the release or autorelease message to the object.

Objects obtained through other methods are set to Auto Release by default, so no operations are required by the programmer.

There is a garbage collection mechanism in objective-C 2.0,

To use garbage collection for a project:

Project information -- Build tab -- Query "garb", "objective-C garbage collection" appears, set its value to "required [-fobjc-GC-only]"

After garbage collection is enabled, the common memory management commands are all empty operation commands and no operation is executed.

You cannot use garbage collection to develop iphone software.

 

5.

Object initialization

There are two ways to create a new object:

[Class Name New]

[[Class name alloc] init]

The two methods are equivalent, but the cocoa convention is to use the latter.

Alloc initializes the memory to 0 while allocating space for the object;

Init method: Initialize instance variables to make the object available. [The return type is ID, and the returned value describes the object to be initialized]

When using new to create a new object, the system must complete two steps:

1. allocate memory for the object, that is, the object obtains a memory block used to store its instance variables;

2. automatically call the init method to make the object available.

 
 

6.

New Features of objective-C 2.0 [applicable only to Mac OS x10.5 and later]

@ Property: Declares the attributes of an object. [In this way, you do not need to write the attribute accessors .]

(It has attributes such as copy, retain, readwrite, and readonly)

@ Synthesize: "Create accessors for this attribute"

Point expression

 
 

7.

Category

Category is a way to add a new method to an existing class.

CATEGORY declaration:

@ Interface nsstring (numberconvenience) // Class Name (category name)

-(Nsnumber) lengthasnumber; // extension method declaration

@ End

When using the original class name, you can call methods in all its classes.

CATEGORY limitations:

1. You cannot add new instance variables to the class;

2. If the method in the category has the same name as the existing method in the class, the method in the class is unavailable and replaced by the new method in the category.

Category:

1. Distribute the implementation of classes to multiple files or frameworks;

2. Create a forward reference to a private method;

[Cocoa does not have a real private method, so the method for implementing a private method is as follows:

Declare the method in the category first, and then implement the method in the implementation of the existing class.

In this way, other methods in this class can use this method, and other external classes will not know the existence of this method .]

3. Add informal protocols to objects.

[Creating an nsobject category is called creating an informal Protocol .]

The delegate is an object. Objects of another class require the delegate object to perform some of its operations.

When a delegate object is triggered at a certain time (an event), the delegate object is automatically notified to execute the delegate method. 

Selector:@ Selector(): The selector is only a method name, but it is encoded in a special way during the objective-C runtime to quickly execute the query. The content in parentheses is the method name.

So the setengine of the car class: the selector of the method is: @ selector (setengine:

How does a delegated object know whether it can process messages sent to it (delegated object?

With the selector, the entrusted object first checks the entrusted object and asks whether it can respond to the selector. If yes, send a message to it.

8.

Protocol:

The formal protocol is a list of named methods.

Protocol adoption means that all methods of the Protocol must be implemented. Otherwise, the compiler will issue a warning.

Formal agreements are likeJavaThe same as in. 

Declarative agreement:

@ Protocal nscopying

-(ID) copywithzone :( nszone *) zone; // method list

@ End

Protocol used:

@ Interface car: nsobject <nscopying, nscoding> // list of protocols to be implemented in brackets

{// Instance variable list}

// Method list

@ End

In objective-C 2.0, there are new features: @ optional, @ required

9.

appkit:

Create an appkit project:

file-new project-Mac OS-Application-cocoa application;

iboutlet and ibaction

both are provided by appkit # defines.

iboutlet does not function and does not compile it.

ibaction is defined as void.

these two are the tags provided for the interface builder and the person reading the code.

The. XIB file is generally called the. NIB file.

. NIB file is a binary file that contains frozen objects.

The. XIB file is a NIB file in XML format.

Related Article

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.