Objective-c Grammar Quick over (1)

Source: Internet
Author: User
Tags constant definition

I have some basic knowledge of C ++ or Java. After passing the oc syntax, they are all the same. I personally think that the difficulty is the memory management of oc. Although ARC is available, it also needs to be learned because there is maintenance of old software.

Based on the C language, a small range of object-oriented syntax has been added (retaining the best part of object-oriented, oc contains less java than java, and java contains less c ++, and c ++ has the most complicated content) , OC is fully compatible with C language, c and oc can be mixed. You can mix C language code in OC code (provided that the oc source file extension is .m), or even C ++ code (not all source files can contain c ++ code, only source files with the source file extension .mm can Contains C ++ code).

Can use OC to develop applications for Mac OS X platform and iOS platform

Keywords

Basically all keywords start with @, 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

String starts with @

For example, @ "Hello" is a string in OC, and "Hello" is a string in C, where @ and the string must be next to each other.

Comment

Comments have the same syntax as C.

nil

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

OC program development process

Edit, compile, link (merge all interrelated .o files together, plus function library), and run.

Similar to c, first write the .m file (the file name can be Chinese), then the compiler compiles, links, and runs.

 

Difference between NSLog and printf

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

2, NSLog will automatically wrap after output, printf will not automatically wrap

3. Use of NSLog requires #import <Foundation / Foundation.h>, which contains the declaration of NSLog function. You don't need to remember it. If you can't remember it, you can compile it. If there is an error, it will prompt what is missing.

4, can only include the main header file of the framework, the effect is equivalent to include all the header files in the framework. The header file is in Xcode, the path is very deep, and it is difficult to find. Using printf requires #include <stdio.h>

#import role (preprocessing)

1. Same as #include, used to copy the content of a file

2, can automatically prevent the file content from being copied multiple times, that is, the header file does not need to be the same as C, add the following preprocessing instructions

#ifndef xxx xxx

#define xxx xxx

#endif
The role of the Foundation framework

A framework necessary for developing iOS and Mac programs. This framework contains many commonly used APIs. The framework contains many header files. If you want to use the contents of the entire framework, you can include its main header file.

#import <Foundation / Foundation.h>
Equivalent to #include import header file. There are also two ways to find <...> and "...".

When a header file is included, when compiling, you need to find that header file. Using this method, when the compiler searches, it will start to search in the standard library of the compiler's installation directory. The folder where the current project is located starts to look, that is, the folder where the source program is located. Some compilers have very strict requirements and cannot be mixed, and some can.

Use of BOOL (can be used as an integer)

The essence of the BOOL type:

typedef signed char BOOL;
BOOL variables have only two values: YES, NO

#define YES (BOOL) 1

#define NO (BOOL) 0
BOOL output (used as an integer);

NSLog (@ "% d% d", YES, NO); // 1 0
There are no boolean types in C, they are in C ++, java, and oc. However, oc's boolean is different from c ++. In C ++, everything that is not 0 is true, and 0 is false. But in Object-c, 1 must be true and be defined by the macro as YES, 0 as false and be defined by the macro as NO.

Therefore, the following code must not get the desired running order.

 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 never equals YES in oc (because YES in oc is 1). Note: BOOL is uppercase, YES and NO are also uppercase, YES in OC is 1, and NO is 0.

Development and mixed development of multiple .m files

It is the same as the multi-file development in C language. Recall that c multi-file development. The constant definition or function declaration is written in the xxx.h file. The function definition is written in the xxx.c file. The main file is written in the main.c file. Program and function calls, and finally #include xxx.h file, compile the main files main.c and xxx.c together.

Object-oriented common terms

Procedure Oriented
Object Oriented
Object Oriented Programming
Facial objects in OC
1) A class is equivalent to a drawing and is used to describe a class of things.

2) Use classes to create objects. Objects are the concrete existence of classes

3) Therefore, object-oriented problem solving should first consider which classes need to be designed, and then how many objects are created using the classes

Define the OC class and create OC objects

Defining a new class is divided into 2 parts:

@interface part;

Describe a class, its data components, and its methods

@implementation part;

The actual code that implements these methods

 

General format of @interface part:

@interface NewClassName: ParentClassName

{

memberDeclarations;

}

methoddeclarations;

@end
General format of @implementation part:

@implementation NewClassName

methodDefinitions;
@end
// NewClassName represents the same name as the class name in the @interface part
There are two major steps to describe a class: the declaration of the class and the implementation (definition) of the class.

Like functions, functions are also declared and defined. Declaring a class requires three major elements: class name, properties, and behavior, similar to C ++.
Naming rules:

Begin with a letter or underscore, followed by any letter, underscore, or 0-9 number combination.

Convention:

Class names begin with a capital letter, and the names are meaningful, such as camel case identification.

The names of instance variables, objects, and methods begin with lowercase letters. Each time a new object is created, a new set of instance variables is created and unique.

Note: There is a * on the right side of the object type. All object variables are pointer types.

The id (universal pointer) type is already predefined as a pointer type, so there is no need to add an *.

Class declaration, a space after the keyword @interface followed by a class name, and then you must write @end at the end to tell the compiler that the class declaration is complete
The class declaration is used to declare the properties (member variables, also called instance variables) and behaviors (methods) of the object
: NSObject inherits a class (in the Foundation framework)
Curly braces are used to write object properties, not methods
Method (behavior); written outside curly braces, before @end
Three elements: method name, parameter, return value (similar to function, sub-declaration and implementation), method declaration is in the class declaration, and cannot be written in curly brackets.
Although the method is similar to the function of c, it is very different from the function
As long as the method is an object method, you must add a minus sign before the declaration, this is the rule!
Any data type in the oc method must be enclosed in parentheses ()
The parentheses of the oc method have a role in enclosing the data type. So-(void) run (); is wrong!
Class implementation, similar to the class declaration syntax, also write @end
The member variables in the object can be integers, so the default initialization is 0
The implementation of the oc method must be written in the implementation of the class, explaining what is in the method.
The (-) or (+) sign at the beginning of the method means:
(-) The method is an instance method (perform some operations on a specific instance of the class);

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

Example declaration of oc general method:

-(void) setNumerator: (int) n
The first represents the method type (object method-), the return type (empty void), followed by the method name (including the colon :), the method accepts the parameter type int and the parameter name n

Note: If there is no parameter, the ":" sign is not used.
If no return type is specified, the default is the id type, and all input parameters are also the id type by default (the id type can be used to refer to any type of object, which is a universal pointer type).

 Example of method declaration with multiple parameters in oc:

-/ + (return type) function_name: (parameter type) parameter1 otherParameter: (parameter_type) parameter2;
If there is only one parameter, declare the type and name of the parameter after:

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

In objective c, for a function with multiple parameters, it can be understood as dividing the name of the function into several parts, and each part is an explanation of the following parameters, which is very convenient and well-known. The official documentation of oc is also, especially the method name with multiple parameters is often very long.

As in C ++ multiple method declarations:

void initializeRectangle (int x1, int y1, int x2, int y2);
I don't know what these parameters mean, but in objective-c, you can declare it like this:

void initializeRectange: (int) x1 LeftUpY: (int) y1 RightBottomX: (int) x2 RightBottomY: (int) y2;
Creating objects with classes

In oc, if you want to perform some actions, you must write a square bracket [], to the left of the square bracket is the name of the class or the name of the class instance, followed by the method (ie the message)

[classOrInstance method];
Car executes the new behavior of the Car class to create objects and allocates memory. Each object has its own storage space to store its own member variables and other elements.
youCar = [Car new]; // An Car class object is created, and the address of the object is returned (returned object). This object exists in memory afterwards.
If you want to manipulate objects in oc, you can only use pointers to operate indirectly!
Car * p = [Car new]; // Save the address in a pointer, p points to an object of type Car
Assign values to the properties of the object pointed to by p
 p-> speed = 200;
Memory analysis (object has members in memory)

[Car new] Every time a new object is created and the address of the object is returned, then a pointer variable should be used to save the address of the object

Car * c = [Car new]; // Use a pointer variable c to point to the Car object in memory
Setting the properties of the car object is the same as using the pointer to the structure to access the structure properties, using->

c-> wheels = 3;

c-> speed = 300;

Changes and state diagrams of objects in memory

Access attributes of members of the oc class:

The oc class attribute is @protected by default. The internal and inherited classes of this class can be accessed, but the external class cannot be accessed. You need to manually set it to public.

@pubic
There is a typical error

OC must not be confused with C ++ and Java. You don't need to add curly braces in the class implementation. You can write the method implementation directly.

 Unlike c ++, the classes of oc occupy a share of memory space!

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

1. The memory of the class is only loaded once (the first time the object is used, the object is loaded Class), and it only contains a list of methods.

2. Inside the storage space of objects of each class in memory, by default there is a pointer called isa pointer, each object has, the role is: point to the class corresponding to this object (storage block of the class to help find the object belongs to Class), so all objects share a method, so the class can be loaded only once. Each object of a member variable has its own share of memory, but methods share a share of memory

3. The process of calling the method:

[person1 walk];
carried out:

Send a walk message to the object pointed by person1, call the object's walk method, and then the object will find the corresponding class along the isa pointer, find the method in the class, find the walk method, go to the corresponding code to execute, and Access the member variables age and weight of the current object in the walk method (because of the member variables, each object has its own copy)

Again: assigning objects to variables of type id is not a problem.

Note: No matter where an object is, it always carries a protected member of its isa (a pointer that can be used to determine the class to which the object belongs), so it can always be determined even if it is stored in a general object variable of type id the type.

Benefits of object-oriented encapsulation
Closer to human thinking
You only need to focus on the object, not the steps
But note: the oc object will not be automatically reclaimed. Once created, it will always be stored in memory unless it is manually released or the program execution is completed. Therefore, the objects created by the function do not disappear. But no pointer to it exists.
Note that in oc, methods and functions are essentially different, don't be confused!
 

Objective-c syntax over (1)

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.