Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've found a few similar questions to this but not relating to XCode.

I am creating an app where clicking a button generates a randomised quote and displays it in a label.

What I'd like to do is have a text file with all of the quotes, then have my app randomly select a quote from that file.

The problem is that my code at present reads the entire contents of the file.

    textHIYP = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
textHIYP.editable = NO;
[self.view addSubview:textHIYP];

textHIYP.text = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Quotes" ofType:@"txt"] encoding:NSUTF8StringEncoding error:nil];

The only other way I can think of doing it is to have an arc4random() code that randomises which file it locates, with each file containing a single quote...but as I want to have over a hundred quotes, this seems less than ideal.

Any suggestions as to how to read a particular line of a text file?

Thanks heaps in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
170 views
Welcome To Ask or Share your Answers For Others

1 Answer

You could read the whole file into an NSString, then split it into an array with componentsSeparatedByString:@" ", keep that it memory, and return a random element of the array when needed. If there are just hundreds (and not, say, millions) of lines, the additional memory used should not be an issue.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...