單例只會對某個類實例化一次/單例類,對單例這個類實例化一次有且僅有一個對象
你單例初始化,只能初始化一次,然後你指向的對象,其實都是指向一個內存地址,也就是同一塊內存,所以都是一樣的/ so。。只能有一個對象,就是實例化的那個 (1)定義單例類singleton [objc] #import <Foundation/Foundation.h> @interface singleton : NSObject //@property (strong,nonatomic) UITextField *value;//最開始的時候把這個value定義為UITextField了,然後在init裡面又沒有初始化它,就取不到值。任何對象都要初始化它才能使用。 @property (strong, nonatomic) NSString *value; //+(id)shareData: +(singleton *)shareData; @end [objc] #import "singleton.h" @implementation singleton static singleton *singletonData = nil; +(singleton *)shareData { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ singletonData = [[singleton alloc] init]; }); return singletonData; } -(id)init { if (self = [super init]) { // self.value = [[UITextField alloc]init]; } return self; } @end (2)ViewController [objc] #import <UIKit/UIKit.h> #import "OneViewController.h" #import "singleton.h" @interface ViewController : UIViewController @property (weak, nonatomic) IBOutlet UITextField *qqTextfield; - (IBAction)go:(id)sender; @end [objc] - (IBAction)go:(id)sender { //單例的使用 singleton *oneS = [singleton shareData]; // oneS.value.text = self.qqTextfield.text; oneS.value = self.qqTextfield.text; OneViewController *oneVC = [[OneViewController alloc]init]; [self presentViewController:oneVC animated:YES completion:nil]; } (3)OneViewController [objc] #import <UIKit/UIKit.h> #import "singleton.h" @interface OneViewController : UIViewController @property (weak, nonatomic) IBOutlet UITextField *oneTextField; @end [objc] - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. self.oneTextField.text = [singleton shareData].value; }