ID type in objective-C

Source: Internet
Author: User

Objective-C has a type called ID, which sometimes operates like void *, but it strictly specifies that it can only be used on objects. Objective-C is different from Java and C ++. You do not need to know the type of an object when calling the method of an object. Of course, this method must exist, which is called the message transmission of objective-C. Objective-c features similar to JavaScript.

In this sense, the ID type is a method unique to objective-C to reference object generics. The following demo:

-(ID) Init {

Self = [Super init];

If (Self ){

[Self setlevel: 10];

}

Return self;

}

Int main (INT argc, const char * argv []) {

// Here, in essence, init returns the ID type and assigns it to OBJ *, which is actually a type conversion.

OBJ * Ob = [[OBJ alloc] init];

ID number;

// Assign a value to the ID type, and then call it through the ID.

Number = ob;

[Number Print];

// Call work well below

Rectangle * rec = [[rectangle alloc] initwithwidth: 10 Height: 20];
Square * sq = [[Square alloc] initwithsize: 15];

// But the compilation below will fail. Note that square inherits the rectangle and is OK according to C ++, but objective-C won't work here. In order to support this syntax, one approach is the rectangle constructor.

// The Return Value of initwithwidth is not the rectangle * type, but is changed to the ID type.

Square * sq = [[rectangle alloc] initwithwidth: 10 Height: 20];

}

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.