my app crashes often in this for-loop:
for (int a = 0; a <= 20; a++) {
NSString * foo = [[NSString alloc]initWithString:[[newsStories objectAtIndex:arc4random() % [newsStories count]] objectForKey:@"title"]];
foo = [foo stringByReplacingOccurrencesOfString:@"’" withString:@""];
foo = [[foo componentsSeparatedByCharactersInSet:[[NSCharacterSet letterCharacterSet] invertedSet]] componentsJoinedByString:@" "];
foo = [foo stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
textView.text = [textView.text stringByAppendingString:[NSString stringWithFormat:@"%@ ", foo]];
}
The code changes a NSString from a NSDictionary and adds it into a textView. Sometimes it first crashes in the second time using the for-loop. What did I wrong?
initWithString: raises an exception if you pass it a nil argument, so if your newsStories dictionary item happens to be missing its title, that will cause a crash (unless you’re catching the exception elsewhere).
Try splitting off the part that retrieves the title and make sure it’s non-nil before passing it to initWithString:
Alternatively, if the newsStories dictionary item’s title object isn’t an NSString instance, that would crash initWithString: as well.