---
title: "Objective-C 创建单例"
author: "wangleyiang"
date: "2013-11-07T12:14:26Z"
tags: ["单例"]
categories: ["编程语言"]
slug: "objective-c"
draft: false
lastmod: "2013-11-07T12:16:01Z"
id: 1972535
url: "https://wangleyiang.iteye.com/blog/1972535"
---

程序开发（Objective－C）中，经常要用到单例，其创建代码如下：

```
static Car *sharedInstance = nil;

#pragma mark Single instance
+ (Car *)sharedInstance {
    if (!sharedInstance) {
        sharedInstance = [[self alloc] init];
    }
    return sharedInstance;
}

+ (id)allocWithZone:(struct _NSZone *)zone {
    @synchronized(self) {
        if (sharedInstance == nil) {
            sharedInstance = [super allocWithZone:zone];
            return sharedInstance;
        }
    }
    return nil;
}
```

 说明：

1. 覆盖allocWithZone:方法的目的是为了防止任何类创建第二个实例；
2. @synchronized指令防止多线程同时调用该代码块；