Facilitating initialization methods and specifying initialization methods in OBJECTIVE-C

Source: Internet
Author: User


Initialization convenience initialization and specifying initialization convenience initialization mode convenient initialization mode one

-(id) initWithFormat: (NSString *) format, ...;
A new string is initialized as the result of the format operation. The following is a small example
// Return a string by format
NSString * myString = [[NSString alloc] initWithFormat: @ "myString has% d
letter ", 8];
 NSLog (@ "% @", myString);
The result is to print out a sentence: myString has 8 letter

Convenient initialization method two
*-(id) initWithContentOfFile: (NSString *) path encoding: (NSStringEncoding) enc error: (NSError **) error
The function is to initialize by reading the content of the file and initialize a string object
encoding is used to specify the encoding format of the file, such as GBK UTF8, etc. In general, there is no special case, use NSUTF8StringEncoding.
If the error parameter is initialized normally, it returns nil, otherwise it returns an error message, which is encapsulated as an NSError object, which can be printed using the% @ format character, or you can use the NSError object method: localizedDescription to print the error information.
Note: error is a pointer to a pointer
The following is an example of initializing by opening a file and reading the contents of the file:

 NSError * error = nil;
 NSString * fileContent = [NSString stringWithContentsOfFile: @ "/ Users / qingyun / Desktop / anotherTest.txt" encoding: NSUTF8StringEncoding error: & error];

NSString * fileContent = [[NSString alloc] initWithContentsOfFile: @ "/ Users / qingyun / Desktop / anotherTest.txt" encoding: NSUTF8StringEncoding error: & error];
      // error is a pointer to a pointer
   if (nil! = error) {
       NSLog (@ "% @", error);
       exit (1);
   }
NSLog (@ "File content:% @", fileContent);
Specifying initialization methods
  
   When subclassing, in order to ensure that the parent class can be initialized normally, it is necessary to override all initialization methods and convenient initialization methods of the parent class, and add the initialization of the member variables of the child class. This will cause the parent class to be modified or added. When the method is initialized, the subclass needs to be modified accordingly. Such a design deviates from the design principle of high cohesion and low coupling.

Specify the initialization function
   A certain initialization method in the class is assigned as the specified initialization function, all initialization methods of this class use the specified initialization method to perform the initialization operation, and the subclass uses the specified initialization method of its superclass to initialize the superclass.
   In general, the initialization method that receives the most parameters is the final designated initialization method because its initialization information is more comprehensive. Therefore, for subclasses, as long as the designated initialization method of the parent class is rewritten, the convenient initialization method can be solved. Cons.

Here is an example to build a QYTire class, which has two member variables, pressure and pattern, and some corresponding methods. In its corresponding header file (.h), the code is as follows:

#import <Foundation / Foundation.h>

@interface QYTire: NSObject
// {
// float myTirePresure;
//}
@property float pressure;
@property float treadth;

-(id) initWithPressure: (float) pressure;
-(id) initWithTreadth: (float) treadth;


-(id) initWithPressure: (float) pressure andTreadth: (float) treadth;
@end
In the implementation file, the code is as follows:

-(id) init
{
    self = [self initWithPressure: 30.5f andTreadth: 20.6f];
    if (self) {
    }
    return self;
}


-(id) initWithPressure: (float) p
{
    self = [self initWithPressure: p andTreadth: 20.6f];
    if (self) {
    }
    return self;
}

-(id) initWithTreadth: (float) t
{
    self = [self initWithPressure: 30.5f andTreadth: t];
    if (self) {
    }
    return self;
}

// Specify the initialization method
-(id) initWithPressure: (float) p andTreadth: (float) t
{
    self = [super init];
    if (self) {
        self.pressure = p;
        _treadth = t;
    }
    return self;
}
Create a new subclass AllWeatherTire, inheriting from QYTire, because it inherits the methods in the superclass, when it wants to use these methods in the subclass, it must override these methods. If you use the specified initialization method, when the parent method appears When changing, you only need to override the specified initialization method in the subclass.

// Header file AllWeatherTire.h
#import "QYTire.h"

@interface AllWeatherTire: QYTire
// {
// float rainHanding;
//
//}
@property float rainHanding;
@property float snowHanding;

-(id) initWithRainHanding: (float) rainHanding;
-(id) initWithSnowHanding: (float) snowHanding;

@end


// The implementation file AllWeatherTire.m
#import "AllWeatherTire.h"

@implementation AllWeatherTire

-(id) initWithPressure: (float) p andTreadth: (float) t
{
    self = [super initWithPressure: p andTreadth: t];
    if (self) {
        self.snowHanding = 300.2f;
        self.rainHanding = 200.3f;
    }
    return self;
}
-(id) initWithSnowHanding: (float) s
{
    self = [self initWithSnowHanding: s andRainHanding: 200.3f];
    if (self) {

    }
    return self;
}

-(id) initWithRainHanding: (float) r
{
    self = [self initWithSnowHanding: 300.2f andRainHanding: r];
    if (self) {

    }
    return self;
}

// Subclasses can also use the specified initialization method
-(id) initWithSnowHanding: (float) s andRainHanding: (float) r
{
    self = [super init];
    if (self) {
        self.snowHanding = s;
        self.rainHanding = r;
    }
    return self;
}

-(NSString *) description
{
    return [NSString stringWithFormat: @ "%. 1f,%. 1f,%. 1f,%. 1f", [self pressure], [self treadth], self.rainHanding, self.snowHanding];
}

@end

Copyright statement: This article is an original article by the blogger and may not be reproduced without the permission of the blogger.

Convenient and specified initialization methods in Objective-C

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.