ARC代码转换 - 这个NumberRef更改是否正确?

时间:2011-12-04 02:06:20

标签: iphone objective-c automatic-ref-counting

我正在使用一个未使用ARC编译的现有库,并且在升级项目时需要转换以下代码行:

CFAttributedStringSetAttribute(text, 
    CFRangeMake(position, length), 
    kCTStrokeWidthAttributeName, 
    [NSNumber numberWithFloat:[[attributes objectForKey:@"stroke"] intValue]]);

使用ARC编译当然产生了一些错误,我修改了代码以使其更加合规。代码更改是否正确?

int strokeInt = [[attributes objectForKey:@"stroke"] intValue];
CFNumberRef strokeNumber = CFNumberCreate(NULL, kCFNumberSInt32Type, &strokeInt);

CFAttributedStringSetAttribute(text, 
    CFRangeMake(position, length), 
    kCTStrokeWidthAttributeName, 
    strokeNumber);

任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:1)

您正在泄露strokeNumber,除非您正在呼叫CFRelease。但是CFNumberNSNumber无关联,因此您可以取消strokeNumber并使用强制转换:

CFAttributedStringSetAttribute(text, 
    CFRangeMake(position, length), 
    kCTStrokeWidthAttributeName, 
    (__bridge CFNumberRef)[NSNumber numberWithFloat:[[attributes objectForKey:@"stroke"] intValue]]);

此外,如果[attributes objectForKey:@"stroke"]恰好是NSNumber,您可以简化为:

CFAttributedStringSetAttribute(text, 
    CFRangeMake(position, length), 
    kCTStrokeWidthAttributeName, 
    (__bridge CFNumberRef)[attributes objectForKey:@"stroke"]);