I need to be able to pull 100's of strings from a plist and display them in a label within my project. I have managed to get this to work pulling data from two different arrays within my plist and then generating a random string to display.
What i want to do now is ensure that no two strings are displayed twice in one session and also be able to set a counter system up that after 5 goes it displays a message.
I was thinking of doing a simple counter for the display message after x amount of turns however when it comes to not displaying duplicates from the array im a little lost. I need it to only basically remove an item from the array (not the plist every time the user presses the button)
- (IBAction)truth:(id)sender {
NSString *path = [[NSBundle mainBundle] pathForResource:
@"test" ofType:@"plist"];
NSDictionary *plistDict = [[NSDictionary alloc] initWithContentsOfFile:path];
NSMutableArray *plistArray = plistDict[@"truth"];
NSDictionary *plistDict2 = [[NSDictionary alloc] initWithContentsOfFile:path];
NSMutableArray *plistArray2 = plistDict2[@"dare"];
plistArray = [plistArray arrayByAddingObjectsFromArray:plistArray2];
NSLog(@"%@", plistArray);
int randV = arc4random() % plistArray.count;
self.joke.text = plistArray[randV];
NSLog(@"dictionary: %@, array: %@", plistDict, plistArray);
}
The problem you have is that every time you are getting a message, you are reading the plists again and recreating plistArray
The correct way would be to save plistArray into a local variable (a property) and only populate it the first time.
Then, if you want to remove an item, you call `[plistArray removeObjectAtIndex: randV];
Edit: code
// In .h file
@property (strong, nonatomic) NSMutableArray * plistArray;
- (IBAction)truth:(id)sender {
if (!self.plistArray) {
NSString *path = [[NSBundle mainBundle] pathForResource:
@"test" ofType:@"plist"];
NSDictionary *plistDict = [[NSDictionary alloc] initWithContentsOfFile:path];
NSArray * plistArray1 = plistDict[@"truth"];
NSDictionary *plistDict2 = [[NSDictionary alloc] initWithContentsOfFile:path];
NSArray *plistArray2 = plistDict2[@"dare"];
self.plistArray = [[plistArray1 arrayByAddingObjectsFromArray:plistArray2] mutableCopy];
}
NSLog(@"%@", plistArray);
int randV = arc4random() % self.plistArray.count;
self.joke.text = self.plistArray[randV];
[self.plistArray removeObjectAtIndex:randV];
NSLog(@"dictionary: %@, array: %@", plistDict, self.plistArray);
}
@property
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments