00-OC

015-CFBridgingRelease简析

2017-06-26  本文已影响55人  AncientMing

上一篇:014-移动支付12-SDK设计-整体结构原理与设计

一、CFBridgingRelease

Moves a non-Objective-C pointer to Objective-C and also transfers ownership to ARC.

把非OC的指针指向OC并且转换成ARC。

二、Declaration

id CFBridgingRelease(CFTypeRef X);

三、Discussion

You use this function to cast a Core Foundation-style object as an Objective-C object and transfer ownership of the object to ARC such that you don’t have to release the object, as illustrated in this example:

使用举例如下:

CFStringRef cfName = ABRecordCopyValue(person, kABPersonFirstNameProperty);
NSString *name = (NSString *)CFBridgingRelease(cfName);

四、相关CFBridgingRetain

Casts an Objective-C pointer to a Core Foundation pointer and also transfers ownership to the caller.

使用举例:

NSString *string = <#Get a string#>;
CFStringRef cfString = (CFStringRef)CFBridgingRetain(string);
// Use the CF string.
CFRelease(cfString);

五、实战使用

字符串分类,让字符串转url

/**
 字符串转url

 @return 由字符串转化成的NSURL
 */
- (NSURL *)url;
/**
 字符串转url
 
 @return 由字符串转化成的NSURL
 */
- (NSURL *)url {
    return [NSURL URLWithString:(NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]", NULL, kCFStringEncodingUTF8))];
}

六、附CFURLCreateStringByAddingPercentEscapes

Creates a copy of a string, replacing certain characters with the equivalent percent escape sequence based on the specified encoding.

创建一个字符串副本,代替并使用指定格式编码。

6.1 Declaration

定义:

CFStringRef CFURLCreateStringByAddingPercentEscapes(CFAllocatorRef allocator, CFStringRef originalString, CFStringRef charactersToLeaveUnescaped, CFStringRef legalURLCharactersToBeEscaped, CFStringEncoding encoding);

6.2 参数

The allocator to use to allocate memory for the new CFString
 object. Pass NULL
 or kCFAllocatorDefault to use the current default allocator.

这个参数传NULL和kCFAllocatorDefault就行

The CFString object to copy.

传一个CFString对象

Characters whose percent escape sequences you want to leave intact. Pass NULL to specify that all illegal characters be escaped.

字符转义,传NULL指定所有非法字符转义。
如例所示,里面的字符在url中是非法的,需要转义。

Legal characters to be escaped. Pass NULL to specify that no legal characters be replaced.

合法字符除外。传NULL指定不合法字符被替换。

6.3 返回值

A copy of originalString replacing certain characters.

一份原始字符串取代了某些字符。

6.4 例子里使用CFURLCreateStringByAddingPercentEscapes刚好合适

下一篇:016-设计模式一:策略模式(Strategy)

上一篇 下一篇

猜你喜欢

热点阅读