2013-01-16 163 views
2

我有以下代码:CFMutableAttributedString设备上(EXC_BAD_ACCESS)运行时崩溃

NSString *name = @"some text goes in here"; 

     CFStringRef string = (__bridge CFStringRef) self.highlightItem_.comment; 
     CFMutableAttributedStringRef comment = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0); 
     CFAttributedStringReplaceString (comment ,CFRangeMake(0, 0), string); 

     CGColorRef blue =[UIColor colorWithRed:128/255.f green:203/255.f blue:255/255.f alpha:1.0].CGColor; 
     CGColorRef gray =[UIColor colorWithWhite:153/255.f alpha:1.0].CGColor; 

     CFAttributedStringSetAttribute(comment, CFRangeMake(0, [name length]),kCTForegroundColorAttributeName, blue); 
     CFAttributedStringSetAttribute(comment, CFRangeMake([name length], [self.highlightItem_.comment length] - [name length]),kCTForegroundColorAttributeName, gray); 

     CTFontRef nameFont = CTFontCreateWithName((__bridge CFStringRef)kProximaNovaBold, 15.0f, nil); 
     CFAttributedStringSetAttribute(comment,CFRangeMake(0, [name length]),kCTFontAttributeName,nameFont); 

     CTFontRef commentFont = CTFontCreateWithName((__bridge CFStringRef)kProximaNova, 15.0f, nil); 
     CFAttributedStringSetAttribute(comment, CFRangeMake([name length], [self.highlightItem_.comment length] - [name length]),kCTFontAttributeName,commentFont); 

     CGContextSaveGState(context); 
     CGRect captionFrame = CGRectMake(0, 0, rect.size.width - 80, commentHeight); 
     CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(comment); 
     CGMutablePathRef captionFramePath = CGPathCreateMutable(); 
     CGPathAddRect(captionFramePath, NULL, captionFrame); 

     CTFrameRef mainCaptionFrame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), captionFramePath, NULL); 

     CGContextRef context = UIGraphicsGetCurrentContext(); 
     CGContextSetTextMatrix(context, CGAffineTransformIdentity); 
     CGContextTranslateCTM(context, 70, self.imageHeight_ + commentHeight + 20); 
     CGContextScaleCTM(context, 1.0, -1.0); 

     CTFrameDraw(mainCaptionFrame, context); 
     CGContextRestoreGState(context); 

     CFRelease(framesetter); 
     CGPathRelease(captionFramePath); 

我不知道为什么,当我在模拟器上它的所有工作运行良好,但是当我在设备上运行,它在这条线上崩溃:

CFAttributedStringSetAttribute(comment, CFRangeMake(0, [name length]),kCTForegroundColorAttributeName, blue); 

任何想法为什么?

+0

我删除了我的答案,我没有看到你已经从UIColor CGColor属性。 –

+0

iOS在模拟器或设备上运行的是什么? – holex

回答

1

所以问题是我没有保留我的CGColor。如果我把CGColorRetain然后它的工作

0

不应该

CFMutableAttributedStringRef comment = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0); 
CFAttributedStringReplaceString (comment ,CFRangeMake(0, 0), string); 

阅读

CFMutableAttributedStringRef comment = CFAttributedStringCreateMutable(
    kCFAllocatorDefault, 
    CFAttributedStringGetLength(string)); 
CFAttributedStringReplaceString(comment, 
    CFRangeMake(0, CFAttributedStringGetLength(string)), 
    string); 

相关问题