/* OK */UIFont *boldFont = [UIFont fontWithName:@"DINPro-Medium" size:14];
assert(boldFont); // just be sure
/* OK */CTFontRef ctBoldFont = CTFontCreateWithName((__bridge CFStringRef)boldFont.fontName, boldFont.pointSize, NULL);
assert(boldFont); // just be sure
/* 1) CGColorRef cgColor = UIColorFromRGB(0x2b776d).CGColor; */
CGColorRef cgColor = CGColorCreateCopy( UIColorFromRGB(0x2b776d).CGColor );
assert(cgColor); // just to be sure
/* OK */NSNumber* underline = [NSNumber numberWithInt:kCTUnderlineStyleSingle];
NSDictionary *ULSubattributes = @{
/* you don't own the kCT strings */(__bridge NSString *)kCTFontAttributeName : CFBridgingRelease(ctBoldFont),
/* ... */ (__bridge NSString *)kCTForegroundColorAttributeName : CFBridgingRelease(cgColor),
/* ... */ (__bridge NSString *)kCTUnderlineStyleAttributeName : underline };
1) iOS pre-iOS6 中存在一个错误,当您仍在使用 CGColorRef 时,ARC 将释放支持 CGColorRef 的 UIColor。我知道这一点,因为我创建了一个 rdar,然后在 iOS 6 中报告为已修复。
PS:这里是 Mike Ash 的一篇不错的博客
编辑:此代码在我的 iOS 演示应用程序中运行良好(部署设置为 5.1 和 6) - 请参阅日志消息。我把 dict 变成了 ivar。
{
UIFont *boldFont = [UIFont fontWithName:@"Helvetica" size:14];
assert(boldFont); // just be sure
CTFontRef ctBoldFont = CTFontCreateWithName((__bridge CFStringRef)boldFont.fontName, boldFont.pointSize, NULL);
assert(boldFont); // just be sure
CGColorRef cgColor = CGColorCreateCopy( [UIColor colorWithRed:0.8f green:0.8f blue:0.8f alpha:0.8f].CGColor );
assert(cgColor);
NSNumber* underline = [NSNumber numberWithInt:kCTUnderlineStyleSingle];
assert(underline);
ULSubattributes = @{
(__bridge NSString *)kCTFontAttributeName : CFBridgingRelease(ctBoldFont),
(__bridge NSString *)kCTForegroundColorAttributeName : CFBridgingRelease(cgColor),
(__bridge NSString *)kCTUnderlineStyleAttributeName : underline };
NSLog(@"ULSubattributes: %@", ULSubattributes);
}
2013-04-12 11:48:20.294 WebViewScrollTester[44147:c07] ULSubattributes: { CTForegroundColor = " [ (kCGColorSpaceDeviceRGB)] ( 0.8 0.8 0.8 0.8 )"; NSFont = "CTFont \nCTFontDescriptor {type = mutable dict, count = 1,\nentries =>\n\t1 : {contents = \"NSFontNameAttribute\"} = {contents = \"Helvetica\"}\n}\n> "; NSUnderline = 1; }
EDIT2:我什至添加了一个 dispatch_after 以显示 ARC 没有发布任何内容:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^
{
NSLog(@"ULSubattributes: %@", ULSubattributes);
} );