PureLayout is not threadsafe

360 Views Asked by At

I subclass UITableViewCell and use PureLayout to apply constraints but the app terminates with the error "PureLayout is not thread safe, and must be used exclusively from the main thread".

In the function...

 initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier 

I have just applied one constraint

[self.label autoSetDimension:ALDimensionHeight toSize:50];

When this is removed, the app doesn't crash

update--- it's probably because I'm calling an API asynchronously

2

There are 2 best solutions below

2
On BEST ANSWER

Wrap your init call in a dispatch_async to the main thread then...

Without seeing the rest of your code.

dispatch_async(dispatch_get_main_queue(), ^{

        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Something"];

    });

But if you are needing to do this I suspect you are going about things the wrong way. What you should be doing is updating the data with the result from your async call and calling reloadData on the tableview.

Something like...

[SomeAPI loadSomeRemoteDataPleaseWithCompetion:^(NSArray *theNewData){

        self.dataArray = theNewData;
        //oh hai im a bad API and dont return in main thread
        dispatch_async(dispatch_get_main_queue(), ^{

            [self.tableview reloadData];

        });

    }];
0
On

Do not try to change your UI inside functions that are not running on the main thread.

You are trying to change a label constraint inside an init and that is your problem: you are not in the main thread.

To solve this problem, add the line that changes your UI inside the awakeFromNib function of the cell and not in the init function.

Wrong:

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    ...
    [self.label autoSetDimension:ALDimensionHeight toSize:50];
    ...       
}

Correct:

- (void)awakeFromNib {
    [super awakeFromNib];

    ...
    [self.label autoSetDimension:ALDimensionHeight toSize:50];
    ...
}