OBJECTIVE-C Overview (upper)

Source: Internet
Author: User

Objective-c (objc) is a clean language. It adds complete object-oriented features to c, but only introduces a limited new syntax (compared to c ++, which is too limited). Another important feature of objc is "dynamic". It can be said that the dynamic characteristics of objc are the cornerstone of other features (Message, Dynamic Binding, Protocols, Categary, Associative References, Selectors). Its object-oriented features are dynamic, so it is more flexible than C ++ and Java.

 

 

-Message-

Talking about objc must start with the news. The syntax of the message also reveals the aesthetic tendency of the objc author, that is, expressing what you want to say (objc does not support operator overloading, function overloading, default parameters and other characteristics. The definition of the message is this:

-(void) setWidth: (float) width height: (float) height;
setWidth is both a function name and a description of the first parameter, and height is a description of the second parameter. Therefore, the message name of objc is listed for each parameter description.

Message call:

[obj setWidth: 20.0 height: 30.0];
The difference between the message and the commonly mentioned method is that the binding of the message is at runtime, and the binding of the method is at compile time. Therefore, the following call:

[nil setWidth: 20.0 height: 30.0];
It is legal but has no effect, similar to an empty sentence.

Furthermore, due to the dynamic implementation of objc, it is possible to determine whether an object has implemented the message at runtime and decide whether to send the message to the object:

 

-(Id) negotiate
{
    if ([someOtherObject respondsTo: @selector (negotiate)])
        return [someOtherObject negotiate];
    return self;
}
<Objective-C Runtime Guider.pdf>
 

-Id-

Any object of objc can be of type id, it is a bit like void * of c. Since objc has a complete dynamic type system, you can find the method, attribute definition information, class inheritance relationship, interface definition, etc. related to the object from any object pointer. So when you define an object, it's less important what type it is. Given the exact type, it helps to do more type checking during the compilation phase. The dynamic part of C ++ is its virtual function table, and objc expands it to complete class information. Therefore, all messages of objc are "virtual functions".

 

 

-Class definition-

Therefore, in order to obtain this dynamic capability, all objc classes inherit from NSObject.

 

@interface ClassName: ItsSuperclass
{
    instance variable declarations
}
method declarations
@end
 

The class method is preceded by ‘+’ and the object method is preceded by ’-’:

+ alloc;
-(void) display;
-(void) setWidth: (float) width height: (float) height;
If you need to reference other classes, you can use forward declarations:

@class Rectangle, Circle;
Can also include header files:

#Import "Rectangle.h"
Class implementation:

#Import "ClassName.h"

@implementation ClassName
method definitions
@end

+ (id) alloc
{
   ...
}

-(BOOL) isFilled
{
   ...
}
Similar to c ++, objc also provides keywords to limit the visible range of member variables. These are: @private, @protected, @public and @package. Since member variables are accessed through setter \ getter, for external code, the access rights of member variables are determined by the property of @propertity (more information can be obtained from baidu).

objc also provides two keywords: self and super, which are used to refer to the definitions (attributes, messages) of this class and the parent class, respectively.

 

 

-Create Object-

Compared to the C ++ constructor, the allocation and creation of objc objects need to be called explicitly:

id anObject = [[Rectanle alloc] init];
For the implementation of init, there are the following conventions:

Return type must be id
Each class preferably has a named initializer (designated initializer), which has the most complete parameter declaration, and other initializers of this class are called to implement it.
The designated initializer of each class must call the designated initializer of the parent class.
For the value of a member variable, use '=' instead of getter and setter methods.
The return value must be self or nil.
When calling the initializer of the parent class, you must pay its return value to self, because the initializer of the parent class may return different objects.
The initializer of this class initializes the member variables defined by this class, and the member variables defined by the parent class make friends with the initializer of the parent class.
When the initialization fails, you can send release to release self (see the second example).
// an class initializer succeed inherits from NSObject
 -(id) init {
    // Assign self to value returned by super ‘s designated initializer
    // Designated initializer for NSObject is init
    self = [super init];
    if (self) {
        creationDate = [[NSDate alloc] init];
    }
    return self;
}
 

-(id) initWithURL: (NSURL *) aURL error: (NSError **) errorPtr {
    
    self = [supper init];
    if (self) {
        
        NSData * data = [[NSData alloc] initWithContentsOfURL: aURL
                                                       options: NSUncachedRead error: errorPtr];
        if (data == nil) {
            // In this case the error object is created in the NSData initializer
            [self release];
            return nil;
        }
        ...
    }
}
 

 

-Protocols-
A protocol is a collection of methods. Several classes, they may belong to different inheritance trees, but they can implement the same protocol.
Sometimes, we don't know the type of the object, but we know what protocol it implements, and we can send it protocol-specific messages.
Definition of agreement:
@protocol MyXMLSupport
-initFromXMLRepresentation: (NSXMLElement *) XMLElement;
-(NSXMLElement *) XMLRepresentation;
@end
The methods specified in the above agreements must be implemented. In fact, the program can use @required and @optional to limit whether the method is required or optional:

 

@protocol MyXMLSupport
@required
-initFromXMLRepresentation: (NSXMLElement *) XMLElement;
@optional
-(NSXMLElement *) XMLRepresentation;
@end
 

Informal agreement:

Informal agreements are defined in categories. Category is intended to be used to dynamically expand the class. When you don't have the definition of the class, or even only the binary file of the class, you want to add a method definition for the class. Therefore these methods can be implemented in separate * .h and * .m files.

Informal protocols are usually declared as categories of NSObject:

@interface NSObject (MyXMLSupport)
-initFromXMLRepresentation: (NSXMLElement *) XMLElement;
-(NSXMLElement *) XMLRepresentation;
@end
Since all classes inherit from NSObject, the above definition will spread to all classes, which is also dangerous.

As an informal protocol, it lacks language-level support, neither type checking at compile time, nor can it determine at runtime whether an object follows an informal protocol.

All methods of the informal agreement are optional. In some cases, when all methods are optional, the informal agreement can also be used, but it is more recommended to use the formal agreement, plus optional keyword.

In short, try to use formal agreements whenever possible.

objective-c overview (on)

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.