0

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

abcf
  • 685
  • 2
  • 10
  • 25

2 Answers2

1

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];

        });

    }];
Warren Burton
  • 17,451
  • 3
  • 53
  • 73
  • wow O_O you're a genius. I chose the second option and it works. Sorry inexperienced af – abcf May 03 '16 at 21:11
  • It's not recommended to do this kind of hacks. You should use PureLayout functions (Or any UI function) inside functions that are run on the main thread, like awakeFromNib. – Gastón Antonio Montes Nov 29 '19 at 17:34
1

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];
    ...
}
Gastón Antonio Montes
  • 2,559
  • 2
  • 12
  • 15