简体   繁体   中英

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.

If you're using Core Text directly you must use CTFont, not UIFont. They are not mutually compatible (ie 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

The EXC_BAD_ACCESS exception is a memory issue, which is often an object (early) release issue, ie access to an already freed object.

If you don't have NSZombies turned on, do that and try again. There are certainly many posts pertaining to them here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM