Search code examples
iosios5core-textnsattributedstringquartz-core

NSAttributedString in CATextLayer causes EXC_BAD_ACCESS (ios 5.0)


I'm having hard time working with CoreText. Don't know, if I'm doing something wrong or if it's iOS' own bug, but here's what I have: in iOS 5.0 this code makes app crash while displaying view

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIFont * font = [UIFont systemFontOfSize:[UIFont systemFontSize]];

    NSDictionary * attrs = @{(NSString *)kCTFontAttributeName:font};

    NSAttributedString * attrStr = [[NSAttributedString alloc] initWithString:@"Test" attributes:attrs];

    CATextLayer * textLayer = [[CATextLayer alloc] init];

    textLayer.frame = self.view.frame;

    textLayer.string = attrStr;

    [self.view.layer addSublayer:textLayer];
}

It makes EXC_BAD_ACCESS and opens CoreText TAttributes::TAttributes(__CFDictionary const*): showing line of assembler where exception occurred.

Am I doing something wrong? I'm struggling with it for almost 8 hours and still no clue what is going on.

UPDATE

It seems like the problem is somehow based on this line

    NSDictionary * attrs = @{(NSString *)kCTFontAttributeName:font};

because when I remove Font attribute and add ForegroundColor attribute it suddenly starts to work. I will try to dig deeply, but still would like some help.


Solution

  • If you're using Core Text directly you must use CTFont, not UIFont. They are not mutually compatible (i.e. there is no toll-free bridge between them).

    I spent an entire day discovering this. My problems were just like what you're experiencing now!

    The wonderful NSAttributedString stuff is, unfortunately, iOS 6 only. So if you want to make a multistyled string and display it in iOS 5, what you are doing is right. But you must use only iOS 5-compatible calls.

    Here's some typical code for making an NSAttributedString that works with CoreText and can be displayed by a CATextLayer on iOS 5:

    https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/iOS5bookExamples/ch23p689styledText1/p579p593styleText1/RootViewController.m