Objective-C: allocate and initialize objects

Source: Internet
Author: User

Similar to C #, OC also has a root type, that is, nsobject, which contains an alloc method and an init method. As the name implies, alloc is used to apply for memory, create an internal structure of an object, and assign the instance variable to 0.

The init method assigns the value of the variable to the default value (it seems to be different from 0), and then executes some other tasks.

Alloc is like entering a car, and init is a fire engine.

Normal Syntax:

Myobject * someobject = [[myobject alloc] init];
[Someobject dosomething];

The other is:

Myobject * someobject = [myobject new];

Write in this wayProgramExecute as usual

Myobject * someobject = [myobject alloc];
[Someobject dosomething];

 

Why? Because the init method defined in nsobject does not initialize anything, it only returns itself. Before the class is used, you need to execute some tasks to use, and init is only a placeholder for these tasks. Nsobject does not initialize anything, but the [[myobject alloc] init] method is still recommended. The initialization method returns an object of the ID type, therefore, the init method and alloc method may not return an object. This technique ([[myobject alloc] init]) is called two-stage creation.

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.