Pourquoi serait retarder une réponse de fil corruption de vue fixe?
-
22-09-2019 - |
Question
6 fois sur 10 mon application iPhone très simple est d'obtenir un affichage corrompu lors du lancement ou se bloque au hasard. Mais il se comporte bien dans le simulateur. La corruption d'affichage ressemble à des polices mal colorées, hors de texte de police, mauvaises couleurs de fond, etc.
Je l'ai trouvé un étrange travail autour .. quand mes retards de fil de 2 secondes avant d'appeler la notification « fait », tout fonctionne à merveille. Le thread lit une page Web et les charges de notification « fait » jusqu'à un PickerView avec des cordes. Alors qu'est-ce qui se passe? Puis-je pas lancer en toute sécurité une tâche de thread viewDidLoad?
- (void) loadWebPage:(NSString *)urlAddition {
NSAutoreleasePool *subPool = [[NSAutoreleasePool alloc] init];
NSString *pageSource;
NSError *err;
NSString *urlString = [NSString stringWithFormat:@"http://server/%@",
urlAddition];
pageSource = [NSString stringWithContentsOfURL:[NSURL URLWithString: urlString]
encoding:NSUTF8StringEncoding
error:&err];
[NSThread sleepForTimeInterval:2.0]; // THIS STOPS THE DISPLAY CORRUPTION
[[NSNotificationCenter defaultCenter] postNotificationName:@"webDoneNotification"
object:nil];
[subPool drain];
}
- (void) webDoneNotification: (NSNotification *)pNotification {
[mediaArray release];
mediaArray = [[NSArray arrayWithObjects:
[NSString stringWithString:@"new pickerview text"],
nil] retain];
[mediaPickerView reloadAllComponents];
[mediaPickerView selectRow:0
inComponent:0
animated:NO];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
mediaArray = [[NSArray arrayWithObjects:
[NSString stringWithString:@"init pickerview text"],
nil] retain];
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
myWebThread = [[WebThread alloc] initWithDelegate:self];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(webDoneNotification:)
name:@"webDoneNotification"
object:nil];
[myWebThread performSelectorInBackground:@selector(loadWebPage:) withObject:@""];
}
Merci!
Mise à jour:. Même un retard de 0,1 secondes est suffisant pour résoudre complètement le problème
La solution
Vous mettez à jour la vue d'un fil d'arrière-plan. C'est ce qui cause vos problèmes; UIKit vues ne sont pas thread-safe. Lorsque vous avez besoin de modifier la vue, le faire dans le thread principal.