Objective-c syntax (1), objective-c syntax

Source: Internet
Author: User
Tags uppercase letter

Objective-c syntax (1), objective-c syntax

There is a certain c ++ or java Foundation. Once the oc syntax is passed, it is the same. In my opinion, the difficulty is the oc memory management. Even with the ARC, you also need to learn, because of maintenance of old software.

Based on the C language, a small scope of object-oriented syntax is added (the most essential part of object-oriented is retained, and there are not many java content in oc, java does not have much content than c ++, and c ++ is the most complicated). OC is fully compatible with c, and c and oc can be mixed. The C language code can be mixed into the OC code (provided that the oc source file extension is. m), even C ++ Code (not all source files can contain c ++ Code, only the source file extension is. mm source file can contain c ++ code ).

You can use OC to develop Mac OS X and iOS applications.

Keywords

Basically, all keywords start with @, and some common keywords

@ Interface, @ implementation, @ end, @ public, @ protected, @ private, @ selector, @ try, @ catch, @ throw, @ finally, @ protocol, @ optional ,@ required, @ class, @ property, @ synthesize, @ dynamic, self, super, id, _ cmd, _ block, _ strong, _ weak

The string starts @.

For example, @ "Hello" is a string in OC, while "Hello" is a string in C, where @ and string must be closely connected.

Note

The syntax of the annotation is the same as that of C.

Nil

Nil in OC is equivalent to NULL in c and c ++.

OC Program Development Process

Edit, compile, and link (merge all the associated. o files and add the function library) to run the program.

Similar to c, first compile the. m file (the file name can be Chinese), then compile, link, and run the compiler.

 

Differences between NSLog and printf

1. NSLog receives OC strings as parameters, and printf receives C language strings as parameters

2. NSLog output will automatically wrap the line.

3. # import <Foundation/Foundation. h> is required to use NSLog, which contains the NSLog function declaration. You do not need to remember it. If you cannot remember it, compile it. If an error occurs, you will be prompted about what is missing.

4. Only the main header file of the framework can be included. The effect is equivalent to that of all header files in the framework. The header file is in Xcode, and the path is very deep. To use printf, # include <stdio. h>

# Role of import (preprocessing)

1. Like # include, it is used to copy the content of a file.

2. The file content can be automatically prevented from being copied multiple times, that is, the header file does not need to be the same as C. Add the following preprocessing commands.

#ifndef  xxx xxx#define xxx xxx#endif

Role of the Foundation framework

A framework essential for developing iOS and Mac programs. This framework contains many common APIs. The Framework contains many header files. If you want to use the content of the entire framework, you can include the main header file.

#import <Foundation/Foundation.h>

There are two ways to search for the # include import header file <...> and "...".

When compiling a file containing a header file, you need to find the header file. In this way, the compiler searches for the file in the standard library of the compiler installation directory, "" This method will start searching for the folder where the current project is located, that is, the folder where the source program is located. Some compilers have strict requirements and cannot be mixed. Others can.

Use of BOOL (can be used as an integer)

The essence of the BOOL type:

typedef signed char BOOL;

There are only two BOOL-type variables: YES and NO.

#define YES (BOOL)1#define NO  (BOOL)0

BOOL output (used as an integer );

NSLog(@"%d %d", YES, NO);//1 0

C has no boolean type, c ++, java, and oc. However, there is a difference between the Boolean value of oc and c ++. In C ++, all non-0 values are true, and false values are 0 values. However, in Object-c, the value 1 must be true, and the macro is defined as YES, and 0 is false, and the macro is defined as NO.

Therefore, the following code cannot obtain the desired running sequence.

 1 #import <Foundation/Foundation.h> 2 BOOL isBool(int, int); 3  4 int main(void) 5 { 6     if (isBool(5, 1) == YES) { 7         NSLog(@"ok"); 8     } 9     return 0;10 }11 BOOL isBool(int x, int y)12 {13     return x - y;14 }

4 is not 1, and will never be equal to YES in oc (because YES in oc is 1). Note: BOOL is capitalized, YES and NO are also capitalized, and YES in OC is 1, NO is 0

Development and hybrid development of multiple. m Files

Similar to the development of multiple files in c language, the definition of constants or function declaration of c multi-file development is written in xxx. h file, function definition written in xxx. c file, main file. c write the main program and function call, and # include xxx. h file, compile the main file main. c and xxx. c file.

Common object-oriented terms

  • Process-Oriented Procedure Oriented
  • Object-oriented Object Oriented (OO for short)
  • Object-Oriented Programming Object Oriented Programming (OOP)
Surface object in OC

1) similar to a drawing, used to describe a class of things.

2) create an object using a class. The object exists as a class.

3) Therefore, the object-oriented solution should first consider which classes need to be designed and how many objects need to be created using classes.

Define OC classes and create OC objects

Defining a new category is divided into two parts:

@ Interface;

Describes the data components and methods of classes and classes.

@ Implementation part;

Actual code for implementing these methods

 

@ Interface:

@interface NewClassName : ParentClassName{memberDeclarations;}methoddeclarations;@end 

@ Implementation:

@ Implementation NewClassNamemethodDefinitions;
@ End // NewClassName indicates the same name as the class name in the @ interface section.

There are two steps to describe the class: class declaration and class implementation (Definition ).

Similar to functions, functions are also defined and declared. Declaring a class requires three elements: Class Name, attribute, and behavior, similar to c ++.

Naming rules:

It must start with a letter or underline, followed by any letter, underline, or 0 ~ 9 combination of numbers.

Conventions:

The class name starts with an uppercase letter and has a meaningful name, such as a camper ID.

Instance variables, objects, and methods are named in lowercase letters. Each time a new object is created, a group of new instance variables are created and unique.

Note: There is a * number on the right side of the object type, and all object variables are pointer types.

The id (Universal pointer) type has been predefined as the pointer type, so you do not need to add a * number.

  • Class declaration. The keyword @ interface is followed by a space with a class name. Then, @ end must be written at the end to tell the compiler that the class declaration is complete.
  • Class declaration is used to declare object attributes (member variables, also called instance variables) and behavior (methods)
  • : NSObject inherits a class (in the Foundation framework)
  • Used to write object attributes in curly brackets.
  • Method (behavior); written out of curly brackets, before @ end
    Three elements: method name, parameter, return value (similar to a function, declaration and implementation), method declaration in the class declaration, and cannot be written in curly brackets.
    Although the method is similar to the c function, it is very different from the function.
    As long as the method is an object method, a minus sign must be added before the Declaration. This is a rule!
    Any data type in the oc method must be enclosed in parentheses ().
    The parentheses of the oc method are used to enclose the data type. So-(void) run (); is wrong!
  • Class implementation, similar to the declaration syntax of the class, also needs to write @ end
  • The member variable in the object, which can be an integer, is initialized as 0 by default.
  • The implementation of the oc method must be written in the class implementation to clarify what is in the method.

The (-) or (+) sign at the beginning of the method indicates:
(-) This method is an instance method (to perform some operations on a specific instance of the class );

(+) Is a class method (that is, a method that executes certain operations on the class itself, such as creating a new instance of the class)

The following is an example of the oc General method declaration:

-(void)setNumerator :(int)n

The first one indicates the method type (Object method-), the return type (empty void), followed by the method name (including colon :), the parameter type int accepted by the method and the parameter name n

Note: ":" is not required if no parameter is required.

If no return type is specified, the default value is id. All input parameters are id by default. (The id type can be used to reference any type of objects, which belongs to the omnipotent pointer type ).

Example of a method declaration with multiple parameters in oc:

-/+ (return type) function_name : (parameter type) parameter1 otherParameter : (parameter_type) parameter2;

If there is only one parameter, the type and name of the parameter are declared:

If there are multiple parameters, there must be one before each parameter:, followed by the parameter type and parameter name.

In objective c, functions with multiple parameters can be understood as splitting the function name into several parts. Each part is an explanation of the following parameters, which is very convenient, the oc official documentation is also well-known, especially the method names with multiple parameters are often very long.

For example, the method declaration for multiple parameters in C ++:

void initializeRectangle(int x1, int y1, int x2, int y2); 

But I don't know what these parameters mean, but in objective-c, you can declare them as follows:

void initializeRectange: (int)x1 LeftUpY :(int)y1 RightBottomX: (int)x2 RightBottomY:(int)y2; 

Create an object using the class

In oc, to execute some behaviors, you must write a brackets []. The left side of the square brackets is the class name or the name of the class instance, followed by a space (that is, a message)

[classOrInstance method];
Execute the new action of the Car class to create an object and allocate memory. Each object has its own storage space to store its own member variables and other elements.
YouCar = [Car new]; // creates a Car class object and returns the object address (returned object ). This object exists in the memory.
To operate objects in oc, you can only use pointers for indirect operations!
Car * p = [Car new]; // Save the address to the pointer. p points to a Car-type object.
Assign a value to the property of the object pointed to by p.
 p->speed = 200;

Memory analysis (the object has members in the memory)

[Car new] each time a new object is created and the address of the object is returned, the address of the object should be saved with a pointer variable.

Car * c = [Car new]; // use a pointer variable c to point to the Car object in the memory.

Set the attributes of a car object, which is the same as accessing the struct attributes with a pointer to the struct. Use->

C-> wheels = 3;

C-> speed = 300;

Changes and status diagrams of objects in memory

Access attributes of oc members:

The default attribute of the oc class is @ protected. The class can be accessed internally and from the inherited class, but cannot be accessed from the outside. You need to manually set it to public.

@pubic

There is a typical error

Oc must not be confused with c ++ or java. You do not need to add curly braces in the class implementation. You can directly write the implementation of the method.

Unlike c ++, the oc class occupies a memory space!

When class is used for the first time, the class is loaded into the memory, that is, the class is allocated memory space before the object is created.

1. The memory of the storage class is loaded only once (when the object is used for the first time, the class of the object is loaded), and only the list of methods is saved.

2. The internal storage space of each class object in the memory has a pointer called isa pointer by default, and each object has the following function: point to the class corresponding to this object (store the memory block of the class to help find the class to which the object belongs), so all objects share a method, so the class can be loaded only once. Each object of the member variable has its own memory, but the method shares the same memory.

3. Process of calling a method:

[person1 walk]; 

Run:

Send a walk message to the object pointed to by the pointer person1 to call the walk Method of the object. Then, the object will find the corresponding class following the isa pointer, find the method in the class, and find the walk method, go to the corresponding code for execution, and access the member variables age and weight (Because of the member variables, each object has its own copy.)

Again, it is no problem to assign an object to the id type variable.

Note: No matter where the object is, it always carries its isa protection member (a pointer that can be used to determine the class to which the object belongs ), therefore, even if you store it in a common object variable of the id type, you can always determine its class.

Benefits of object-oriented Encapsulation
  • Closer to human thinking
  • You only need to focus on objects and do not need to follow the steps
  • However, note: oc objects are not automatically recycled. Once created, they are stored in the memory until they are manually released or the program is executed. Therefore, the objects created by the function will not disappear. But no pointer to it exists.
  • Note: methods and functions are essentially different in oc. Do not confuse them!

 

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.