iOS.常用设计模式.01.单例模式

使用单例模式的类:

UIApplication

UIAccelerometer

NSUserDefaults

NSNotificationCenter

NSFileManager

NSBundle等

Singleton.h

#import <Foundation/Foundation.h>

@interface Singleton : NSObject

// 始终返回同一个Singleton的指针
+ (Singleton *)sharedManager;

@property (strong,nonatomic) NSString *singletonData;


@end

Singleton.m

#import "Singleton.h"
@implementation Singleton
@synthesize singletonData = _singletonData;
static Singleton *shareManger = nil;

/**
 该方法采用了GCD(Grand Central Dispatch)技术,这是一种机遇C语言的多线程访问计数。
 dispatch_once函数就是GCD提供的,它的作用是在整个应用程序生命周期中只执行一次代码块。
 dispatch_once_t是GCD提供的结构体,使用时需要将GCD地址传给dispatch_once函数。
 dispatch_once函数能够记录该代码快是否被调用过。
 **/
+ (Singleton *)sharedManager
{
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        shareManger = [[self alloc] init];
    });
    return shareManger;
}

@end

SingleAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [Singleton sharedManager].singletonData = @"Singleton init";
    
    NSBundle *bundle = [NSBundle mainBundle];
    NSLog(@"bundle = %@",bundle);
    return YES;
}

SingleViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSLog(@"viewDidLoad print : %@",[Singleton sharedManager].singletonData);
    NSBundle *bundle = [NSBundle mainBundle];
    NSLog(@"bundle = %@",bundle);
}
原文地址:https://www.cnblogs.com/cqchen/p/3775777.html