Initialize and Singleton in Object-c
To put it simply, the initialize function is called only once during initialization of the same class.
The Code directly describes the role of initialize.
Create an InitTest class
InitTest. m
#import "InitTest.h"@implementation InitTest+ (void)initialize{ NSLog(@"InitTest : initialize className : %@",[self class]); }- (id)init{ self = [super init]; if (self) { NSLog(@"InitTest : init"); } return self;}@end
Create an InitTest subclass, InitTestChild.
Next, let's create an experiment and add the following code to viewDidLoad in ViewController. m:
InitTest *iTest = [[InitTest alloc] init]; InitTest *iTest1 = [[InitTest alloc] init]; InitTest *iTest2 = [[InitTest alloc] init]; InitTestChild *child = [[InitTestChild alloc] init];
Result
The initialize of the parent class is called once and the subclass is called once. So let's think about how to create it in other classes? Will initialize be called again? Create a New View Controller. SecondeVC <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + U2Vjb25kZVZDLm08YnI + cda-vcd4kpha + PC9wPgo8cHJlIGNsYXNzPQ = "brush: java;" >#import "SecondeVC. h "# import" InitTest. h "@ implementation SecondeVC-(void) viewDidLoad {[super viewDidLoad]; NSLog (@" test whether initialize function is called during initialization of other classes "); initTest * iTest = [[InitTest alloc] init]; InitTest * iTest1 = [[InitTest alloc] init]; InitTest * iTest2 = [[InitTest alloc] init]; NSLog (@ "It turns out no, it seems to be a spoiler in advance");} @ end
Add the following code at the bottom of viewDidLoad in ViewController. m:
UIButton * btn = [UIButton buttonWithType: UIButtonTypeRoundedRect]; [btn setTitle: @ "" forState: UIControlStateNormal]; btn. frame = CGRectMake (0, 0,100, 50); [btn setTitleColor: [UIColor blackColor] forState: UIControlStateNormal]; [btn addTarget: self action: @ selector (test) forControlEvents: UIControlEventTouchUpInside]; [self. view addSubview: btn];
Redirection method:
- (void)test{ [self presentViewController:[[SecondeVC alloc] init] animated:YES completion:^{ }];}
Result:
According to the above experiment, initialize is called only once, so we can use this feature when creating a single instance.
A singleton can be written as follows:
static InitTest *initTest = nil;@implementation InitTest+ (void)initialize{ NSLog(@"InitTest : initialize className : %@",[self class]); if (initTest == nil) { initTest = [[InitTest alloc] init]; }}+ (InitTest *)defaultManager{ return initTest;}
End
Code: http://pan.baidu.com/s/1sjpxhSD
Original article: http://blog.csdn.net/qqmcy/article/details/41941429