[Oc learning diary] Singleton mode, oc learning Diary
First, let's take a look at the concept of Singleton mode.
The Singleton mode ensures that only one object (only one address) exists in the system.
The following is an example of a student.
To ensure that there is only one object in the system, you must override the object creation method and object COPY method.
1 # import <Foundation/Foundation. h> 2 // because the copy method needs to be rewritten, follow the copy Protocol 3 @ interface Student: NSObject <NSCopying, NSMutableCopying> 4 + (id) create; // declare Method 5 @ end for object Creation
Next, let's look at the implementation process of these methods.
Note:
1. You must first create a static Global Object (ensure that only one address is supported)
2. When you override the creation methods of alloc and new, an error occurs when you create a class name. Therefore, you must use super
3. To prevent multi-threaded operation conflicts, use @ synchronized to avoid
1 # import "Student. h "2 // first create a static Global Object 3 static Student * stu = nil; 4 @ implementation Student 5 + (id) create // Method 6 for object creation {7 @ synchronized (self) // prevents multi-thread operation conflicts 8 {9 if (stu = nil) {10 stu = [[Student alloc] init]; // if the object is empty, a new object is created. Otherwise, only one object 11} 12 is returned; 13} 14} 15 // rewrite alloc and new object Creation Method 16 + (instancetype) allocWithZone :( struct _ NSZone *) zone17 {18 @ synchronized (self) 19 {20 if (stu = nil) {21 stu = [[super allocWithZone: zone] init]; // if the object is empty, create a new object; otherwise, return, ensure that only one object 22} 23 return stu; 24} 25} 26 // rewrite the shallow COPY method 27-(id) copyWithZone :( NSZone *) zone28 {29 return stu; 30} 31 // rewrite the deep COPY method 32-(id) mutableCopyWithZone :( NSZone *) zone33 {34 return stu; 35} 36 @ end
Main function implementation
Although many student methods are defined in the main function, all objects have only one space.
1 #import <Foundation/Foundation.h> 2 #import "Student.h" 3 int main(int argc, const char * argv[]) { 4 @autoreleasepool { 5 Student *stu = [[Student alloc]init]; 6 Student *stu1 = [[Student alloc]init]; 7 Student *stu2 = [Student new]; 8 Student *stu3 = [stu copy]; 9 Student *stu4 = [stu mutableCopy];10 NSLog(@"\n%@\n%@\n%@\n%@\n%@",stu,stu1,stu2,stu3,stu4);11 }12 return 0;13 }
Main function Running Effect
2015-06-05 09:17:48.274 day26_01[643:12774] <Student: 0x100304460><Student: 0x100304460><Student: 0x100304460><Student: 0x100304460><Student: 0x100304460>