ARC 基础(下)

ARC 基础(下)

一、ARC与Block

Blocks 和 ARC 结合起来效果很好。实际上,ARC 使得在使用 blocks 时比从前更简单。

正如你可能知道的,blocks 最初在栈上创建。如果你想要保持一个 block 超过目前范围依然 可以被使用,你不得不把它复制到堆里通过[copy]或者 Block_copy()函数。现在 ARC 自 动实现。 

复制代码
 1 #import <UIKit/UIKit.h>
 2   typedef void (^AnimatedViewBlock)( CGContextRef context,
 3   CGRect rect, CFTimeInterval totalTime, CFTimeInterval deltaTime); 
4 @interface AnimatedView : UIView 5 @property (nonatomic, copy) AnimatedViewBlock block; 6 @end 7 8 #import "AnimatedView.h"
9 @implementation AnimatedView
10 @synthesize block; 11 - ( void)dealloc 12 { 13 NSLog(@"dealloc AnimatedView" ); 14 } 15 @end
复制代码

二、单例 

复制代码
 1 @interface GradientFactory : NSObject
 2 + ( id)sharedInstance;
 3 @end
 4 
 5 + (id)sharedInstance{
 6     static GradientFactory *sharedInstance;
 7     if (sharedInstance == nil){
 8         sharedInstance = [[GradientFactory alloc] init];
 9     }
10     return sharedInstance;
11 } 
复制代码
复制代码
多线程下的单例
1 + ( id)sharedInstance { 2 static GradientFactory *sharedInstance; 3 static dispatch_once_t done; 4 dispatch_once (&done, ^{ 5 sharedInstance = [[ GradientFactory }); 6 return sharedInstance; 7 }
复制代码

Dispatch 库的 dispatch_once()方法以确保对象的 alloc 和 init 确实只被执行一次,即使同一时刻多个线程尝试去执行这个 block。 

 
三、创建你自己的静态库 

选择 New Project。选择 iOSFramework & LibraryCocoa Touch Static Library 工程模版。

原文地址:https://www.cnblogs.com/lee4519/p/4255088.html