ios8,nsarray , Shuffle NSArray


Shuffle NSArray

Question:

Tag: ios8,nsarray

I got an NSMutableArray with a rather small number of objects that varies from 1 to max 20.

When user taps a button I want to select one random object and display it. I've tried shuffling the array:

srandom(time(NULL));
for (NSInteger x = 0; x < [array count]; x++)     {
    NSInteger randInt = (random() % ([array count] - x)) + x;
    [array exchangeObjectAtIndex:x withObjectAtIndex:randInt];

}

And then select a random index using arc4random() but I get many repetitions. I do not want to removeObjectAtIndex as this would only reduce my array to zero and then crash. Is there a way to repopulate the array with the same objects once reached zero and start over again?

Thanks


Answer:

I managed to "solve" my issue by doing the following: It maybe messy but I would like some input on this.

NSUInteger randomIndex = arc4random()% [_someArray count];

    if (array.count == 0) { //check if array is empty and add the randomIndex
        [array addObject:@(randomIndex)];
        randomTitle = [[_someArray objectAtIndex:randomIndex] myText];

        // NSLog(@"array is empty");
        // NSLog(@"my array content %@", array);
    }

    else if (array.count > 0 && array.count < _someArray.count) {//check if array has already an object and check if this is unique and add it to the array. if not run the loop again.

          NSLog(@"array is betwen 0 and _someArray.count");

        if([array indexOfObject:@(randomIndex)] == NSNotFound) {
            [array addObject:@(randomIndex)];
       randomTitle = [[_someArray objectAtIndex:randomIndex] myText];

          //  NSLog(@"unique number in array");
        }

        else {

            [self loopBackTheAction];

            // NSLog(@"number is alreday in array");
        }
    }

   else if (array.count == _someArray.count) {//check if the array is full and empty it. run the loop again.

       [array removeAllObjects];
       [self loopBackTheAction];

       //  NSLog(@"array is full running again the loop");
    }

Related:


How to i create new arrays using swift?


ios,arrays,swift,ios8
I'm not exactly sure what I am looking for, so I'm just going to give you an example... Inside App Lets say I am making a shopping list app. In the app, you can create as many shopping lists as you like, and in those shopping lists, you can add...

iOS 8 simulators not visible in XCode 7 beta


ios8,xcode7
I'm using the XCode 7 beta that Apple released during WWDC2015, and it looks like iOS8 simulators are not there in it. I tried downloading them using the Xcode > Preferences > Downloads > Components, but it doesn't list the simulators. I have Xcode 6.3.2 also on the mac, and...

Parse.com Framework Sort Date Next Birthday


ios,swift,parse.com,ios8
Need to sort on iOS by date using Parse.com but I need to order them based on the next birthday for a specific person. I tried to add the day and month with the current or next year and that helped but that will be a manual process, any recommendations...

Set Images Randomly for buttons from array and take button's cgrect's from aray


ios,objective-c,nsarray
I have 42 buttons in my storyboard and I have take array of images. In this array there are total 7 images. NSArray *arrimg=[NSArray arrayWithObjects:@"book.png", @"lock.png", @"Exclamation.png", @"game.png", @"Music.png", @"Videos.png", @"Camera32.png", nil]; So how could I take random images every time on button? Should I take button collection or do...

Cannot invoke 'canEvaluatePolicy' with an argument list of type '(LAPolicy)' Swift2.0 Xcode 7


ios,swift,ios8
I have a problem with canEvaluatePolicy function. I have declared this function like this : func canEvaluatePolicy(policy: LAPolicy) { do { try authenticationObject.canEvaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics) } catch let error as NSError { print("Error: \(error.domain)") } } But when I want to use it like this: if authenticationObject.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics) { I have an error:...

Wikitude does not work. Poi do not change the position on phone position change


ios,objective-c,ios8,augmented-reality,wikitude
I am trying to integrate AR poi view with Wikitude in my app. As html I used a file from the example 4_PointOfInterest_4_SelectingPois. It should render a few point around my location. It does it, but all points stay in the same position all the time, although I changed my...

Core Data and a UIActivityViewController


objective-c,core-data,nsmutablearray,nsarray,uiactivityviewcontroller
I have my app that is using core data to persist data. I have a UIActivityViewController setup on my main VC. Everything is working as I expect it to. My question is when you go to grab items from a core data model, how do you have it give you...

Move UIToolbar with keyboard iOS8


xcode,ios8,uitoolbar
I have a UIToolbar at the bottom of my ViewController that is inherited from the self.navigationController. I show it in my ViewController in the viewWillAppear: method using this code: [self.navigationController setToolbarHidden:NO animated:NO]; self.navigationController.toolbar.backgroundColor = [UIColor blackColor]; self.navigationController.toolbar.tintColor = [UIColor blackColor]; self.navigationController.toolbar.barStyle = UIBarStyleBlackOpaque; After that, my ViewController has both programmatically...

UISearchController: show results even when search bar is empty


ios,iphone,ios8,uisearchcontroller
As I understand, the default behaviour of UISearchController is: On tapping search bar, background is dimmed and 'cancel' button is shown. SearchResultsController is not shown till this point. SearchResultsController is displayed only if search bar is not empty. I want to display SearchResultsController even when search bar is empty but...

Why does didUpdateLocations: only have one location after locationManagerDidResumeLocationUpdates:


ios8,cllocationmanager
I have location services working in iOS8. It is set for kCLLocationAccuracyBest using startMonitoringSignificantLocationChanges to restart when in the background and startUpdatingLocation for accuracy. When I set pausesLocationUpdatesAutomatically = YES, the location services get paused and resumed as expected. However, the following call to didUpdateLocations: only has one location in...

Test-Flight App beta testing time limitations


ios,iphone,ipad,ios8,testflight
I need to submit my binary files over the air without pushing app to app-store. one solution is using enterprise program, Test-Flight App Beta Testing we can send binary files to external users to limit of 1000. My Questions is : will apple take beta review (following apple guidelines) of...

iOS 8 Autolayout - Visual Format Language how to add constraint to superview's edge


ios,swift,ios8,autolayout,nslayoutconstraint
Can I pin my view to my superView's edge instead of its layout margin through VFL? Can I be even flexible to toggle "Relative to margin" on myView as well? NO VFL (this is what I want to achieve with Visual Format Language): var constraintLeft = NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.Left,...

create a popup window with just a textview/string and a button SWIFT ios 8


iphone,swift,ios8,popup,xcode6
I am very new to ios 8 and swift but I have not found a way to make a simple popup window whenever a button is pushed. I payed for tutorials and they still don't cover it. All i would like is for when the user pushes a button (the...

Restrict app for iPhone devices lower than iPhone 5 with iOS 8 or 7 in AppStore


iphone,ios8,app-store
I planned to develop application with targeted devices iPhone 5/5S, iPhone 6/6+ . I don't want my application to be runnable on iPhone 4S. Can i able to achieve that? I googled some sites , they were mentioned that we can restrict older version mobiles like iPhone 3GS using front...

NSArray? doesn't have member named “Generator”


ios,swift,nsarray
I am getting a weird error from this segment of the code: let path = NSBundle.mainBundle().pathForResource("SampleData", ofType: "plist") let dataArray = NSArray(contentsOfFile: path!) for dict: AnyObject in dataArray{ ...} ...

Passing String array to a function


ios,swift,nsarray
I am trying to pass an array to a function: var array:[String] = [] // fill the array array.append(uniqueId as String) // pass the array to a function: GamePrefrences.setLevelsArray(array) My function is declares like this: func setLevelsArray(arr:[String]) { GamePrefrences.levels_array = arr } But on the line i try to call...

Autolayout works great on iOS 8, crashes on iOS 7


ios,ios7,ios8,autolayout
I have an issue where a screen with autolayout that works great on iOS 8 - but crashes on iOS 7. All subviews are configured in the XIB. The error message is: Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to install constraint on view. Does the constraint reference...

UITableview with more than One Custom Cells with Swift


swift,uitableview,ios8,xcode6
As absolute beginner I have to ask those questions: I want to use a UItableview with different custom TableviewCells. One Cell should have an image and a label. Another cell should have two label. A third cell should have a dayPicker. I don't have to create Tage cell in the...

Why is boundingRectWithSize wrong when using UIFont preferredFontForTextStyle?


ios8,nsstring,uilabel,uifont
I have found that a call to boundingRectWithSize is extremely incorrect, missing an entire additional line, when called with NSFontAttributeName : [UIFont preferredFontForTextStyle:UIFontTextStyleBody]. However, using the font [UIFont fontWithName:@"Helvetica Neue" size:17.f], it is just fine. Here is test code showing the bug: - (void)viewDidLoad { [super viewDidLoad]; NSString *measureText =...

UILabel text isn't updated when modal re-appears


ios,iphone,swift,ios8
I've created a reusable modal UIView as a singleton object, but am having trouble changing the text of a label it contains. When the modal appears a second time, the new text appears over the old text. I'm guessing this is due to the fact that the label is only...

Sort NSArray to a particular sequence using an NSComparisonResult


ios,objective-c,nsarray,comparator
I'm trying to sort my arrays with a particular sequence using an NSComparisonResult. I'm unable to figure out how to achieve the sequence I'm wanting. I'm trying to weight Emojis towards the top (sequence of Emojis doesn't matter), followed by A-Z letters with giving a weight towards lowercase before uppercase,...

Using the device simulator for iOS 8 with Xcode 7


ios8,xcode7,ios9
I thinking about port my App to Swift 2 and Xcode 7. But the device simulator only targets iOS 9 and I see no way to download iOS 8. I have parallel Xcode 6.3 installed. Is there any way to test and debug my app under iOS 8 with the...

A Plugin to view PDF document in iOS cordova based application


ios,iphone,ios8,phonegap-plugins,cordova-plugins
Can please suggest a working plugin to view PDF in iOS Cordova based application. I have tried many of PDF related plugins: https://github.com/siegfriedbolz/cordova-plugin-file-opener2.git https://github.com/RandyMcMillan/PDFViewer but of no use..My application stopped at loading. Lastly with I have tried with pebois/phonegap-plugin-PDFViewer: I have installed using : "cordova plugin add com.lesfrancschatons.cordova.plugins.pdfreader" In index.html:...

Bluemix authentication ios8 with google and facebook


facebook,authentication,ios8,bluemix,google-authentication
I am trying to implement two types of authentication from an iOS8 device in the bluemix platform. I succeeded in adding one type of authentication: google. I am using a ADVANCED MOBILE ACCESS module, and I am at the User Authentication part. It looks from a dashboard like I can...

Parsing JSON into a usable format


swift,nsarray,nsdictionary,nsurl
I'm currently downloading data from a server and I'm not sure how to get the response that I'm getting back into the format that's expected by the method that I'm working with. Could someone guide me on what I would need to do to get all of the items in...

Cannot subscript a value of type [CLPlacemark] with an index type int


ios,xcode,swift,ios8,xcode7
I would like to retrieve the current location. I work with on swift Xcode 7. I looked PLUSIEUR tutorials, but every time they use the same method. Here is my code and my error: ! Error : Cannot subscript a value of type [CLPlacemark] with an index type int import...

Remove “heightForRowAtIndexPath” for iOS8


ios,ios7,ios8,deprecated,heightforrowatindexpath
I'm trying to solve this problem for two days before finding the solution. Here it is. ====== Hi everyone, I actually manage the height of my tableViewCell in iOS7 with the delegate method heightForRowAtIndexPath: Now, in iOS8 I use the property tableView.rowHeight = UITableViewAutomaticDimension with autolayout and it works great...

How to disable the Copy/Hide feature in UIImagePickerController when long pressing a image …?


ios,swift,ios8,uiimagepickercontroller,ios8.3
- Actually am using UIImagePickerController for my usecase,and if i long press any picture ,it shows Copy/Hide option (as shown in the sample image) - I dont want the Copy/Hide feature. Guide me with some suggestions if u too have encountered :)... Thanks in advance...iOS Geeks...PLZ refer my code snippet...

Fatal error when unwrapping CLLocation Location Coordinate


ios,iphone,swift,ios8,optional
I currently have a test application to teach myself Core Location. It is an app with a button which will either show your location when you press a button, or an alert when location services are off. I get a fatal error (unexpectedly found nil when unwrapping option value) When...

Switch between views using a Tabbar


ios,xcode,swift,ios8
I have an iOS application with a Tab Bar, and two subview. My first view is a Table View. So, I want to switch to the second view when I click on a cell of the first view, and keep the TabBar visible. When I do that using "Show" segue...

View set as inputAccessoryView throws exception when added back into normal view


ios,ios8,uikeyboard,inputaccessoryview
I have a text view, some decorations etc. in a view and I want that view to dock on keyboard, just like any other messaging app. When I'm about to display my text view, here is how I attach my view to the keyboard: -(BOOL)textViewShouldBeginEditing:(UITextView *)textView{ UIView *inputView = self.textInputView;...

Swipe up to show button in UITableView?


ios,swift,uitableview,ios8,uicollectionview
I'd like to place a button at the top of a UITableView or UICollectionView, but only shown when swiped up beyond the first row. Usually you see scroll to refresh or a search bar there, but I'd like to put a button there for another functionality. How can I do...

NSPredicate with bitmask for filtering NSArray


ios,objective-c,nsarray,nspredicate,photokit
I'm trying to test whether some particular asset collections contain only one media type/subtype using an NSPredicate. The: testForPhotosPredicate works just fine, however when trying to use the testForPanoramasPredicate it fails with the message: Unable to parse the format string "mediaSubtypes & %i" How can I use a bitmask in...

Error after update to Swift 1.2


ios,xcode,swift,ios8,xcode6.3.2
I updated shortly to Swift 1.2 which comes with Xcode 6.3.2 and wrote a few lines of code: let originView:UIView! override init() { super.init() } init(sourceView:UIView, menuItems:Array<String>){ super.init() originView = sourceView } This code runs perfect till I updated the new version of Xcode (6.3.2). Now I get the following...

Objective C - How do I convert this NSArray to an NSDictionary so I can look up city names by zip code?


ios,objective-c,arrays,nsarray
I use Parse as my backend, and have a cloud function (written in javascript) that just returns an array var providerZIPToCity = [ {zip:"48393", city:"WIXOM, MI"},{zip:"48116", city:"48116, MI"},{zip:"48114", city:"BRIGHTON, MI"},{zip:"48189", city:"WHITEMORE LAKE, MI"},{zip:"48178", city:"SOUTH LYON, MI"},{zip:"48168", city:"NORTHVILLE, MI"},{zip:"48167", city:"NORTHVILLE, MI"},{zip:"48375", city:"NOVI, MI"},{zip:"48374", city:"NOVI, MI"},{zip:"48165", city:"NEW HUDSON, MI"},{zip:"48377", city:"NOVI, MI"},{zip:"48390", city:"WALLED...

NSObject class conforms to protocol contained in NSArray with Swift


swift,nsarray,protocols,swift2,swift-array
I would like to create a method in Swift that returns an array of NSObject objects that conform to a protocol. I've tried something like this: func createManagers() -> [Manager] { let result = NSMutableArray(capacity: self.classes.count) (self.classes as NSArray).enumerateObjectsUsingBlock { (object: AnyObject!, idx: Int, stop: UnsafeMutablePointer<ObjCBool>) -> Void in //...

Core Location and UITableView performance issues in iOS 8


objective-c,uitableview,google-maps,ios8,core-location
I have a view controller that contains two views: a map view using the Google Maps API and a UITableView. The view controller fetches a list of location objects from Google Maps within a certain radius of a particular location and plots them on the map view as markers and...

Auto Rotation iOS 8 Navigation Controller


objective-c,iphone,ios8,uinavigationcontroller,autorotate
I have certain viewControllers which are managed by a UINavigationController (push and pop). I want to restrict different viewControllers to different orientations like the first one should be only in Portrait, second in portrait, third in landscape and fourth can be portrait and landscape both. I set a ViewController on...

Blur Effect on TableViewCell when scroll


ios,objective-c,uitableview,ios8,uiimageview
Right now I'm using LBBlurredImage to blur an image, but I want to change to iOS8's UIVisualEffectView to blur instead. I'm having a hard time implementing, any ideas? Implemented with LBBLurredImage: - (void)updateData { // Set up Screen self.screenHeight = [UIScreen mainScreen].bounds.size.height; //UIImage *background = [UIImage imageNamed:@"gray"]; UIImage *background =...

NSMutableArray adds same NSDictionary multiple times


ios,objective-c,for-loop,nsarray,nsdictionary
I am looping through an array, getting two items and putting them in a dictionary, and then add them to an array, but it keeps adding the last item of the array for the number objects in the array, even though when I log the dictionary inside the loop it...

Check if array contains part of a string in Swift?


arrays,swift,nsarray
I have an array containing a number of strings. I have used contains() (see below) to check if a certain string exists in the array however I would like to check if part of a string is in the array? itemsArray = ["Google, Goodbye, Go, Hello"] searchToSearch = "go" if...

Overwriting NSMutableArray loaded from NSUserDefaults


objective-c,arrays,nsmutablearray,nsarray,nsuserdefaults
So I'm having real problems overwriting an array stored in NSUSerDefaults. Basically I have a checklist of 100 items (defined by bools in an array(which are actually strings at the moment)) and I need to save if each item is checked so when the app loads, the checklist remains as...

Pass data from one view controller to the next WITHOUT a segue in swift


iphone,swift,uiviewcontroller,ios8,segue
So I have an app that where you choose a button in the first screen it will bring you to another screen depending on which one you chose on the first one. Because I have these possible different layouts I can't just use a segue from one button to the...

canEvaluatePolicy Extra argument 'error' in call Swift Xcode 7


ios,xcode,ios8,xcode7
I work with Xcode 7 with swift and I would use the Touch Id. Only I have a error when I use canEvaluatePolicy. I understand my error, I call an argument too. Only if I do not call, it makes me a error because I did not manage my error...

Parsing a Dictionary of Arrays from a Plist file


ios,objective-c,nsarray,nsdictionary
I am trying to work with a specific data layout. We use a plist file which is setup in the following way: Root (Dictionary): - 1.1 (Array) -- Item 0 (Dictionary) --- Title --- Icon -- Item 1 (Dictionary) --- Title --- Icon - 1.2 (Array) -- Item 0 (Dictionary)...

When creating new tableView entry the constraints don't work


uitableview,ios8,nslayoutconstraint
I have a Master-Detail application that uses CoreData. Everything is hooked up fine and works as expected. There is just one problem with the display when adding a new entry. On the left is the Master's TableView with the entries and on the right is the Detail's View, where the...

Getting error in Adjust library, Integrated with Pods


objective-c,ios8,cocoapods
I am getting this error: ld: library not found for -lPods-Adjust clang: error: linker command failed with exit code 1 (use -v to see invocation) I added this to my Podfile: pod 'Adjust', :git => 'git://github.com/adjust/ios_sdk.git', :tag => 'v4.2.5' I have installed pods successfully, but still get the above error....

iOS 8 Swift 1.2 and Parse - Attempt to present UIAlertController on ViewController whose view is not in the window hierarchy


ios,objective-c,swift,parse.com,ios8
There are many questions on Stack concerning this issue, but none of them seem to solve the issue I'm having. I am using ParseUI for the login and signup portion of my application. What I would like to have happen is for a UIAlertController to be presented when a user...

How to get a specific object from data structure based on Index


ios,objective-c,nsarray,nsdictionary
I am creating a custom UIPageViewController which uses a custom setup. The data structure that I have is parsed into the following format: { "1.0" = ( { detail = "Detail 0"; icon = "Pull to Refresh"; title = "Item 0"; }, { detail = "More easily refresh a subscription...

Opening and closing form animation


ios,ios8,core-animation,ios-animations
Is this animation possible in iOS, any third party API's for that? ...