Objective-c Learning Notes _ inheritance, initialization method, convenience builder

Source: Internet
Author: User


First, inheritance


Upper layer of Inheritance: parent class, inherited lower layer: subclass. Inheritance is one-way and cannot inherit from each other. Inheritance has transitivity: a inherits from B,b inherited from C,a with B and C features and? Subclasses can inherit all the characteristics and behaviors of the parent class.


examples
Hit the Zombies. Demand:
1, define the normal zombie class:
Instance variables: Total Zombie blood volume, zombie loss per time.
Methods: The method of initialization (total blood volume), blood loss and death were hit.
2. Define a Roadblock zombie class:
Instance variables: Total Zombie blood volume, Zombie bleed, props, weakness.
Methods: The method of initialization (total blood volume), the beating blood loss, loss of equipment, death.
3, define the bucket zombie class:
Instance variables: Total Zombie blood volume, Zombie bleed, props, weakness.
Methods: The method of initialization (total blood volume), the beating blood loss, loss of equipment, death.
4, create the normal zombie object in MAIN.M, set the total blood volume 50, each time the blood loss is 3, no props.
5, in the MAIN.M to create a roadblock zombie object, set the total blood volume 80, the amount of blood loss is 2, set props for roadblocks.
6, in the main.m to create a bucket zombie object, set the total blood volume 120, the amount of blood loss is 1, set props for the drum.


If you define three classes: Normal zombie, barricade zombie, iron bucket Zombie. They will have a lot of repetitive instance variables and methods, which are not only physical, but also unscientific. Object-oriented provides inheritance syntax, can be large simplified code. The common methods and instance variables are written in the parent class, and the subclasses only need to write their own instance variables and methods. Inheritance guarantees both the integrity of the class and the simplification of the code.


Inheritance implementation
#import <Foundation / Foundation.h>
               / * Child class * / / * Parent class * /
@interface OrdinaryZombie: NSObject
@end 
#import "OrdinaryZombie.h"
               / * Child class * / / * Parent class * /
@interface RoadblockZombie: OrdinaryZombie
@end 
Inheritance Features


Only single inheritance is allowed in objective-c. A class without a parent class is called a root class, and the root class in Objective-c is NSObject (ancestor).



Inherited content: All instance variables and methods. If the subclass is not satisfied with the implementation of the parent class method, you can override the (overwrite) method of the parent class.


Inheritance tree




Implementation of the Law of inheritance




Self, super


Self and Super are keywords in the objective-c language.



Super is a compiler directive, not an object.



Role: Give super message, can hold the method implemented in the parent class.



Subclasses can override the parent class's methods, namely: the subclass has its own implementation, the implementation of the parent class inherits, if you want to use the implementation of the parent class, send a message to super.



Self: Calls its own methods and properties, always representing the object that invokes the method.



The simple example code used by self and super is as follows:


-(instancetype) initWithName: (NSString *) name
                          sex: (NSString *) sex
{
     / *
      * Detailed explanation [super init]
      * Instance variables defined in the parent class are initialized by requesting an initialization method from the super
      * The message requesting the initialization method from the super connects all the objects on the inheritance tree
      * The variables of the parent class are initialized before the variables of the child class
      * For example: When the CollegeStudent object is initialized, it will initialize NSObject, Student, CollegeStudent in turn.
      * For the initialization method, please refer to the following content of this blog post
      * /
     self = [super init];
     if (self) {
         _name = name;
         _sex = sex;
     }
     return self;
}
Second, the method of initialization


There are two steps to creating an object using Objective-c:


    1. memory allocation (space): Allocates a memory address dynamically for a new object.
    2. Initialize: Assigns the initial value to this memory space.


The initialization method is used only once for the entire life cycle of an object. Initialization method naming usually begins with Init; The initialization method can assign an initial value to an instance variable at the time the object is created, and the return of the initialization method can only be an ID (or instancetype) or this class object, not void. A class can have more than one initialization method.



The complete initialization method, the sample code is as follows:


-(instancetype) initWithName: (NSString *) name
                          sex: (NSString *) sex
{
     // Send init message to super: execute the init method implemented in the parent class
     self = [super init];
     if (self) {
         // initialization settings
         _name = name;
         _sex = sex;
     }
     // return the initialized object
     return self;
}


Attention:


    • There is no association between a class and a class prior to learning inheritance, so the initialization method has noself = [super init];typeface and assigns a value to the instance variable individually.

    • After learning inheritance, a common instance variable is declared in the? class. As a parent class, you should have your own initialization method that assigns an initial value to these common instance variables.

    • The subclass defines an instance variable other than the public instance variable in the parent class. In the initialization method of the body, priority is given to super to send the INIT message, initialize the public variable, initialize it successfully, then initialize the body-specific variable to complete the initialization of all instance variables.

Initialization process
    1. In the initialization method of the subclass, the priority is the initialization method of the parent class.
    2. The initialization method of the class is called again in the method of the initialization of its parent class, which is called up to the NSObject class.
    3. After the initialization of the topmost level is complete, the second level of initialization is completed by returning to the initial method of the second layer. After the initialization of the second layer is complete, go back to the initialization method of the third layer, and then follow the initialization method until the initialization method of this class is complete.
Characteristics of the initialization method
    • The initialization method is the "-" number method.

    • The return value type is ID or instancetype.

    • Start with Init.

    • can take 0 to more parameters.

    • Internal implementation: First, super initialization method, and then initialize?? Variable, return self.

Third, the convenience of the construction device


The convenience constructor is encapsulated on the basis of the initialization method, which encapsulates the creation process of the object. The convenience constructor is the "+" sign method, which returns an instance of this type, with the method name beginning with the class name. there can be 0 or more parameters. The internal implementation encapsulates the alloc and initialization methods. Make it more concise.


The implementation of the convenient constructor


1. Declaration and implementation of the convenience builder.


+ (instancetype)personWithName:(NSString *)name
                           sex:(NSString *)sex;


+ (instancetype)personWithName:(NSString *)name
                           sex:(NSString *)sex
{
    Person *person = [[Person alloc] initWithName:name sex:sex]; return person;
}


2. Create an object for the convenience constructor.


Person *person = [Person personWithName:@"小红" sex:@"女"];


In fact, the convenience of the convenience of the constructor is not only the amount of code reduction, but also the convenience of memory operations , if you create an object with a convenient constructor, then after the use of the object is not released, after the automatic release of the pool, the object is automatically destroyed, before the automatic release of the pool destroyed, we hold the object, Regardless of when the object is released (this is the content of objective-c memory management, the blogger will explain in detail in the following blog post).


The appendix begins with an example of "Hit Zombies" code implementation


This example uses the inheritance realization, the topic request is more simple, please read the code carefully.



The normal zombie class OrdinaryZombie.h code is as follows:


#import <Foundation / Foundation.h>

@interface OrdinaryZombie: NSObject
{
@protected
     NSInteger _fullOfBlood; / * Total blood volume * /
     NSInteger _lossOfBlood; / * blood loss per time * /

     NSString * _equipment; / * props * /
     NSString * _weakness; / * Weakness * /
}

/ * Instance variable setter, getter method * /
-(void) setFullOfBlood: (NSInteger) fullOfBlood;
-(NSInteger) fullOfBlood;

-(void) setLossOfBlood: (NSInteger) lossOfBlood;
-(NSInteger) lossOfBlood;

-(void) setEquipment: (NSString *) equipment;
-(NSString *) equipment;

-(void) setWeakness: (NSString *) weakness;
-(NSString *) weakness;

/ * Initialization method (total blood volume) * /
-(id) initWithBlood: (NSInteger) fullOfBlood;

/ * Battered blood loss * /
-(void) attacked;

/ * Death * /
-(void) death;

/ * Lost equipment * /
-(void) loseEquipment;
@end 


The normal zombie class ORDINARYZOMBIE.M code is as follows:


#import "OrdinaryZombie.h"

@implementation OrdinaryZombie
-(void) setFullOfBlood: (NSInteger) fullOfBlood
{
     _fullOfBlood = fullOfBlood;
}

-(NSInteger) fullOfBlood
{
     return _fullOfBlood;
}

-(void) setLossOfBlood: (NSInteger) lossOfBlood
{
     _lossOfBlood = lossOfBlood;
}

-(NSInteger) lossOfBlood
{
     return _lossOfBlood;
}

-(void) setEquipment: (NSString *) equipment
{
     _equipment = equipment;
}

-(NSString *) equipment
{
     return _equipment;
}

-(void) setWeakness: (NSString *) weakness
{
     _weakness = weakness;
}

-(NSString *) weakness
{
     return _weakness;
}

-(id) initWithBlood: (NSInteger) fullOfBlood
{
     _fullOfBlood = fullOfBlood;
     return self;
}

-(void) attacked
{
     _fullOfBlood-= _lossOfBlood;
     if (_fullOfBlood <= 0) {
         _fullOfBlood = 0;
     }
     NSLog (@ "Remaining blood volume:% ld", _fullOfBlood);
}

-(void) death
{
     NSLog (@ "Ordinary Zombie, death");
}

-(void) loseEquipment
{
     NSLog (@ "Lose equipment");
}
@end 


Roadblock Zombie class RoadblockZombie.h code is as follows:


 
#import "OrdinaryZombie.h" @interface RoadblockZombie : OrdinaryZombie @end


Roadblock Zombie class ROADBLOCKZOMBIE.M code is as follows:


#import "RoadblockZombie.h"

@implementation RoadblockZombie
-(void) death
{
     NSLog (@ " zombies, death");
}

-(void) loseEquipment
{
     NSLog (@ " obstaclezombies");
     [super loseEquipment];
}
@end 


Iron Bucket Zombie Class MetalBucketZombie.h code is as follows:


#import "OrdinaryZombie.h"@interface MetalBucketZombie : OrdinaryZombie@end


Iron Bucket Zombie Class METALBUCKETZOMBIE.M code is as follows:


#import "MetalBucketZombie.h"

@implementation MetalBucketZombie
-(void) death
{
     NSLog (@ "Iron barrel zombie, death");
}

-(void) loseEquipment
{
     NSLog (@ "Iron bucket zombie");
     [super loseEquipment];
}
@end 


The MAIN.M code is as follows:


#import <Foundation / Foundation.h>
#import "OrdinaryZombie.h"
#import "RoadblockZombie.h"
#import "MetalBucketZombie.h"
int main (int argc, const char * argv []) {
    @autoreleasepool {
            / * Normal zombie * /
        OrdinaryZombie * ordZom = [[OrdinaryZombie alloc] initWithBlood: 50];
        / * Blood loss per time * /
        [ordZom setLossOfBlood: 3];
        while (1) {
            if ([ordZom fullOfBlood] == 0) {
                [ordZom death];
                break;
            }
            [ordZom attacked];
        }

        / * Roadblock zombies * /
        RoadblockZombie * roadZom = [[RoadblockZombie alloc] initWithBlood: 80];
        / * Blood loss per time * /
        [roadZom setLossOfBlood: 2];
        / * Equipment type * /
        [roadZom setEquipment: @ "路 ROAD"];
        while (1) {
            / * If 50 drops of blood remain * /
            if ([roadZom fullOfBlood] <= 50) {
                / * Lost equipment * /
                [roadZom loseEquipment];
                / * Set blood loss to normal zombie * /
                [roadZom setLossOfBlood: [ordZom lossOfBlood]];
                break;
            }
            [roadZom attacked];
        }
        while (1) {
            if ([roadZom fullOfBlood] == 0) {
                [roadZom death];
                break;
            }
            [roadZom attacked];
        }

        / * Iron Barrel Zombie * /
        MetalBucketZombie * metalZom = [[MetalBucketZombie alloc] initWithBlood: 120];
        / * Blood loss per time * /
        [metalZom setLossOfBlood: 1];
        / * Equipment type * /
        [metalZom setEquipment: @ "铁罐"];
        while (1) {
            / * If 50 drops of blood remain * /
            if ([metalZom fullOfBlood] <= 50) {
                / * Lost equipment * /
                [metalZom loseEquipment];
                / * Blood loss becomes normal zombie * /
                [metalZom setLossOfBlood: [ordZom lossOfBlood]];
                break;
            }
            [metalZom attacked];
        }
        while (1) {
            if ([metalZom fullOfBlood] == 0) {
                [metalZom death];
                break;
            }
            [metalZom attacked];
        }
    }
    return 0;
} 


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.



Objective-c Learning Notes _ inheritance, initialization method, convenience builder


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.