Objective-C syntax, objective-c

Source: Internet
Author: User
Tags try catch

Objective-C syntax, objective-c

I started to learn how to develop the iPhone. Although I Already Have Swift, I still honestly learned Objective-C. I started to use C as the programming language. Later I learned C # and Java, now I want to learn Objective-C. This is just some simple notes, not just grammar books.

Code File

There are three types of Objective-C code files: "*. h "header file ;"*. m "is a common source code file, which can contain Objective-C and C code;" *. mm is also a type of source file, which can contain Objective-C, C, and C ++ code.

The simplest HelloWorld
1 #import <UIKit/UIKit.h>2 #import "HGAppDelegate.h"3 4 int main(int argc, char *argv[])5 {6     printf("Hello world\n");7     NSLog(@"Hello world");8 }

Replace the familiar # include pre-processing command with # import, but the angle brackets "<", ">" and double quotation marks have the same meaning as before, the printf statement can still enter the classic Hello world. In Objective-C, there is a new method-NSLog (@ "Hello world "); classes starting with the NS prefix are pre-defined classes, such as the NSString string and NSArray. NSLOG passed in the parameter is also "Hello world", but added a @, which is the method of Objective-C string, if you want to declare a string variable with an initial value @ "Hello world ",

NSString *str=@”Hello world”;
Basic Data Type

The basic data type of Objective-C is the same as that of C. int is an integer, char is a character, float is a single-precision floating point, and double is a double-precision floating point, there is a difference between short and long, which are written in Objective-C in short int and long int. Here there is a long double type with double precision. The unsigned operator adds an unsigned prefix, which is written as an unsigned int.

Special Data Type
  • Id is a pointer type, which is similar to the Object type in C #/Java and can point to any reference type.
  • BOOL has only two values, YES and NO, which represent 1 and 0. In C, these two values also represent true and false.
  • SEL points to the pointer of the function, and the initial value is defined as follows:
SEL sel = @ selector (method signature)

Or

SEL sel = NSSelectorFromString (method name string)

The call is in the following format:

[obj performSelector:sel withObject: nil];

The above obj is an object instance, sel is a SEL type variable, and nil is the default value of the obj object. If you are safe, you must first determine whether the obj object has that method before calling, then, call the following method, which returns a Boolean value, where true exists, and vice versa.

[obj respondsToSelector:sel]:

If you want to obtain the method name pointed to by the SEL variable, you can call the following method, which returns a string.

NSStringFromSelector (sel variable ):
  • Nil, NiL, and NSNull nil are the same as NULL in C and point to a NULL pointer. It is an object and an object with nothing. Nil is a class that represents NULL, is a Class; NSNull appears in the Set, which represents the empty element of the set.
Process control statement

The two statements switch and foreach are described here, because they are different between C # and Java.

  • The Switch statement is the same as the switch statement in C. After each case, you do not need to use break. After the switch statement is completed and jumped out, it will execute the code in the next case in sequence, until the break is encountered or the end of the statement is reached. The case here is not followed by a string like Java.
  • The Foreach foreach statement is similar to the C # statement and is also the variable name of the element type item in set ). Unlike C #, the bitwise object can be used to modify the traversal set. However, after the change, the enumerator does not update the retrieved set, therefore, if you delete some elements that are just traversed, a null reference exception may occur.
Class

The definition of the Objective-C class is divided into two operations: declaration and implementation. The definition of the interface and the implementation are similar.

  • Class Declaration
@ Interface ClassName: NSObject {// field definition} // declaration of methods, attributes, and other Members @ end
  • Class implementation
@ Implementation ClassName // implementation of methods, attributes, and other Members @ end
Method

The method declaration syntax is as follows:

+(void)methodName(paraType1)paraName1 and:(paraType2)paraName2; 

+ Represents the static method,-represents the instance method, and the following brackets represent the return type. For example, the preceding method returns void with null values; the method name is always in front of the parameter. The method name of Objective-C is special. According to the method stated above, its method name is methodName and. The parameter is in the form of :( ParaType) ParaName, if no parameter exists, the method name is followed by a semicolon. The following method is used to call the object, and the object instance name is used to call the object.

[objIns methodName:value1 and:value2]; 
Access Method

The get/set method must be used to obtain or set private fields. In Java, the getter/setter method must be declared to implement encapsulation in object-oriented programming, in Objective-C, there are also getter/setter methods, which are called access methods.

For example, if the field int count is available, the corresponding access method is

-(void) setCount: (int)couValue;-(int) count; 

The Setter method is the field name corresponding to set +, and the setter directly has the same name as the field. You can use ["]" in the form of common square brackets to call a method that is similar to C # and Java midpoint ". ". If the vertex method is used, it can directly keep up with the field name, as shown in

MyClass.count=12;Int count=myclass.count; 
Attribute

If an attribute is declared, the system automatically generates the getter/setter Method for it. This is similar to the C # attribute, but the syntax format is quite different. Similar to the definition of a class, it has two parts: declaration and implementation.

  • Statement
@ Property (modifier) int count;
  • Implementation

@synthesize count;

If you want to specify the attribute to encapsulate the field by line during implementation, you can use the following form. The following shows the encapsulation of the count field, remember to add underscores (_) to the regular expression "_"

@synthesize count=_count; 

You can specify modifiers when declaring them. They can be separated by commas (,). The modifiers and their functions are as follows:

  • Readwirte: available for read and write;
  • Readonly: Read-only;
  • Strong: Strong reference refers to the reference we usually use in C # and Java, that is, this object will be GC only when it is not referenced by any field;
  • Weak: Weak reference. Even if the object is referenced by a field, it may be GC;
  • Copy: assign a value to only one Copy instead of itself;
  • Assign: When you Assign values through setter, the Reference Counter of this object is not added, which is applicable to the NSString type and basic data type;
  • Retain: the previous referenced object will be released during the call, but the reference counter will add 1;
  • Nonatomic: indicates that this attribute does not consider thread security issues.

If you do not use the getter or setter method automatically generated by the system, you can specify the signature of the getter method and setter method defined by yourself in the modifier, as shown in

@property(getter=mygetter,setter=mysetter:) int count;
Block

It is also called a code block. The declared syntax is as follows:

ReturnType (^ BlockName) = ^ (paraType1 para1, paraType2 para2) {/* Code content */};

The left side of the equal sign is equivalent to declaring the block variable. The right side of the equal sign is equivalent to the block literal value. The effect of the block is similar to the lumbling expression. It is called as if the method is called in C/C #.

BlockName(para1,para2);
Protocol

Syntax:

@ Protocol ProtocoName // method declaration @ optional // optional implementation // method declaration @ required // required implementation // method declaration @ end

This is similar to the interface, which is implemented in the following form of class declaration

@interface ClassName:NSObject<ProtocoName1,…..>
Category

Syntax:

@ Interface ClassName (CategoryName) // method declaration @ end // other code @ implementation ClassName (CategoryName) // method declaration @ end

It is used to extend the defined class. ClassName is the defined class and the class to be extended. CategoryName is the class name. If the method in the class encounters the same method as the method signature, it will overwrite the original method. The class members are limited to methods, and the fields cannot be defined. If the method is covered, the covered scope is the entire program.

Self and supper
  • Self is a class hidden parameter, similar to this of Java and C #. When calling a method, search for the method in this class first. If not, search for the method in the parent class.
  • Super is a pre-compiled command, similar to C # and Java's super, but not exactly the same. super here does not represent a reference to the parent class, but searches for the parent class before calling the method, if no, search for the parent class again. It only has the effect of C #/Java when calling the method. In essence, it still references the current class.
Memory Management

Call at the beginning

NSAutoreleasePool *pool=[ [NSAutoreleasePool alloc] init]; 

End Time

[pool release];

Constructor

[[ClassName alloc] init];

Release object

[ClassInsName release]; 

Rules: 1) objects created by using alloc or copy must be release when they are used up; 2) objects not created by themselves should not be release; 3) After retain objects, to reallocate, the two must be symmetric, and the number of referers must be release.

Exceptions and errors

The exception handling of Objective-C is similar to that of C # And Java. It is also composed of try catch finally statement blocks. throw is used to throw an exception. The format is as follows:

@try{  }@catch(NSException *ex){@throw}@finally{   }

The keyword is the same as the keyword of C #, but an "@" is added. The @ thorw In the catch Block is only used for demonstration.

In Objective-C, NSError makes people feel similar to NSException. They are all related to errors, but in fact they are different in usage. NSException is an exception and records the exception information, exceptions occur in the program, which will cause the program to get stuck. NSError is an error that records the error information. For example, if a method fails to be called, The NSError object of the incoming method will be filled with the relevant error information, and NSError will not cause the program to be stuck, however, if NSException is not captured, the program will be stuck. NSException can be thrown and captured. NSError does not throw or capture the concept.

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.