Objective-C (learning objective-C)

Source: Internet
Author: User

I wanted to translate it, but I saw some translations on the Internet, so I directly reproduced it.

Original post address: http://www.i-alive.com/post/45/

English address: https://developer.apple.com/library/ios/#referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/_index.html#//apple_ref/doc/uid/TP40007594

Objective-C is a superset of C language, that is, it supports basic C language syntax.
Class definition and implementation are placed in the header file and the source file respectively. The extension of the header file is. h; the source file is. m; and A. MM file is used to put C ++ code.

Classes)

The definitions of objective-C classes are divided into two parts: declaration and implementation:
The Interface part contains the class declaration, instance variable definition, and class-related methods. Interfaces are usually in. H files;
The code implementation part contains the code of the class method, which is placed in the. M file.

The class declaration syntax is provided.

Class myclass inherits the base class nsobject.
The class Declaration starts with @ interface, followed by the class name and the inherited base class; The Declaration ends with @ end.
Put the instance variables (or member variables) of the class in braces ({&});
The class method is declared out of braces.
Each line of statements ends with a semicolon.

Objective-C supports both strong and weak types. A strong type does not need to be added. If it is weak, it is declared by "ID". variables declared by this type can be installed at all times, this is probably the meaning.

Methods and messaging (methods and messages)

Methods:
The objective-C class can declare two methods: class method and instance method.
The instance method is called only after the instance is declared, and "-" is used for the declaration;
The class method can be called directly using the class just like a static method, and "+" is used for declaration ".
Syntax for method declaration:

 

Message:
I always think this message is strange. It is awkward to translate it. Forget it. Don't worry. Let's just talk about it.
The method to call a method is to send an object message (messaging an object ). Message is the method signature. All messages sent to objects are dynamically called, which is also a method for implementing polymorphism in objective-C.

[myArray insertObject:anObject atIndex:0];

As shown in the preceding example, a message is wrapped in a bunch of brackets ([&]) for one call. In the brackets, the object receiving the message is on the left (myarray), and the message is on the right (that is, insterobject: anobject atindex: 0 ).

Messages can also be nested. For example, a parameter can be a message. For example, the message execution result can be passed to the parameter, or the message can be used as the receiver. the following line of code is the same, in this way, the code is concise.

[[myAppObject theArray] insertObject:[myAppObject objectToInsert] atIndex:0];

Objective-C uses the "." operator to operate access methods (accessor methods) to obtain or set object statuses. Generally, the access method is:
-(Type) prropertyname // read
-(Void) setpropertyname :( type) // set

The following is the sample code:

// Use ". "operator calls the access method [myappobject. thearray insertobject: [myappobject objecttoinsert] atindex: 0 ". "The operator calls the access method myappobject. thearray = anewarray;

Class method implementation example:

@implementation MyClass - (id)initWithString:(NSString *)aName{    self = [super init];    if (self) {        name = [aName copy];    }    return self;} + (MyClass *)createMyClassWithString: (NSString *)aName{    return [[[self alloc] initWithString:aName] autorelease];}@end

Note: In objective-C, Nil is equivalent to null. For example, nsmutablearray * myarray = nill.

Declared Properties)

Declaring a property is much easier than declaring an access method.
The attribute declaration is put together with the method declaration and is defined by @ property.
You can set attributes, such as read-only objects or copy objects during reading, as follows:

@property BOOL flag;@property (copy) NSString *nameObject;  // Copy the object during assignment.@property (readonly) UIView *rootView;  // Declare only a getter method.

For each readable attribute, a method with the same name is automatically set for reading;

For each writable attribute, a method in the form of setpropertyname is automatically set, starting with set, followed by an attribute name with uppercase letters.

In the implementation part of the class, you can use "@ synthesize" to instruct the compiler to generate the corresponding method of the attribute.
You can declare it in two ways:

@synthesize flag;@synthesize nameObject;@synthesize rootView;
@synthesize flag, nameObject, rootView;

In general, attributes reduce the amount of code. If we use the access method to implement it, we will do almost the same thing, and it will write a bunch of implementation code. Declare with @ property, and use @ synthesize to generate the acquisition and setting methods during compilation, which is obviously simpler.

Strings (string)

As a super set of C, it supports C-style strings. But generally, C-style strings are not used.
The string is transmitted as an nsstrings object.
There are many advantages of using nsstrings to wrap strings. For example, you can use some built-in methods to process strings, such as sorting by length, Unicode, and printf format.
Because strings are often used, objective-C provides a shorthand method to create an nsstring object.
As follows (use @):

NSString *myString = @"My String\n";NSString *anotherString = [NSString stringWithFormat:@"%d %@", 1, @"String"]; // Create an Objective-C string from a C stringNSString *fromCString = [NSString stringWithCString:"A C string"                                   encoding:NSASCIIStringEncoding];

Protocols)

Protocols is similar to the interface in C # In my understanding:

  • Can be implemented by any class;
  • Only interface is defined, no implementation, no instance variables, and the Implementation part is handed over to the inherited class;
  • APIS that are often used to specify delegate objects;
  • Declaration method:
@interface MyClass : NSObject  {}@end

The following code describes the direct relationship between the Protocol, delegate, and other objects:

@protocol MyProtocol- (void)myProtocolMethod;@end

Suppose there is a uiaplication class that implements some methods of an application. To receive some notifications of this application, we do not need to inherit this uiaplication class. This class calls the method, send the notification to the delegate object. Another object that implements the delegate protocol (uiaplicationdelegate protocol) method will receive notifications and provide a suitable response information.
To implement an interface, you only need to use "<>" to hold the protocol name and put it behind the inheritance class. The declaration part of the class does not need to be declared again for the Protocol method.

 

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.