user563496 user563496 - 18 days ago 5
iOS Question

Do you know how to randomly populate a table with an array of pictures?

I'm trying to create a memory game and I'm stuck with no idea how to randomly populate my cells with pictures from an array. I've just started out Xcode programming mainly for the iOS and I have searched for days on Stack Overflow but I can't seem to find an answer. Either that or I don't really understand what you professionals have said and explained.

Could anyone kindly please enlighten me?

Answer

This code will take an NSArray containing the pictures and produce a new array containing the pictures in random order. Then, you can save the new array and use it in your data source for your table.

NSArray *pictures; //Array containing all of the pictures to display
srandomdev();
NSArray *randomPictures = [pictures sortedArrayUsingComparator:(NSComparisonResult)^(id obj1, id obj2) {
    long val = random();
    if(val & 1) return NSOrderedAscending;
    return NSOrderedSame; //or NSOrderedDescending
}];