1

I create a NSThread to change the text of textField,and i make sure the NSThread is not main thread.Though,the textField'text changed.Shouldn't the UI update must be on the main thread?

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UITextField *textField;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(changeText) object:nil];
    NSLog(@"%@ %d",thread,[thread isMainThread]);
    [thread start];
}

- (void)changeText {
    self.textField.text = @"this is thread";
}

3 Answers3

4

If you make UI calls from a thread that's not the main thread, the results are undefined. It may work, it may not. Sometimes it will even crash your app. Don't do that.

Another problem:

Your code that runs on a new thread doesn't create an autorelease pool so any objects you create may be leaked.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
1

Check your log, it actually creates warnings for you.

This application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread. This can lead to engine corruption and weird crashes.

Yes, it may work so far, but it will cause crashes or other un-predictable result when the application gets complicated.

Elvin
  • 1,133
  • 6
  • 15
0

If you are updating UI in a background thread.. It may work or may not work depends on the burden on the main thread.At any point of time it may cause the crash. So to be safe UI related updates should be on MainThread only.