2014-09-12 70 views
1

這就是我想要做的事。每次我的viewDidLoad開始時,獲取7個隨機,非重複的數字。我得到了它的創建隨機量,但我一直在試圖清除的NSMutableSet加載時得到一組全新的,我有麻煩了。 NSLog清楚地顯示NSMutableSet中沒有任何內容,但它總是以相同的順序出現相同的數字?無法清除/重置NSMutableSet?

// Create set 
NSMutableSet *mySet = [NSMutableSet setWithCapacity:6]; 

// Clear set 
NSMutableSet *mutableSet = [NSMutableSet setWithSet:mySet]; 
[mutableSet removeAllObjects]; 
mySet = mutableSet; 

NSLog(@"mutableSet: %@", mutableSet); // Shows nothing 
NSLog(@"mySet: %@", mySet); // Shows nothing 

// Assign random numbers to the set 
while([mySet count]<=6){ 
    int Randnum = arc4random() % 7+1; 
    [mySet addObject:[NSNumber numberWithInt:Randnum]]; 
} 

NSLog(@"mySet1: %@", mySet); // Always shows 5,1,6,2,7,3,4 ??? 

回答

1

NS(Mutable)Set無序集合,它不保留的元素的順序,因爲他們插入。所以,你的輸出只能說明集包含從1 號到7

你有不同的選擇,讓您的預期輸出。

  1. 改爲使用NSMutableOrderedSet

  2. 使用一組跟蹤已經發生的數字,而且還可以存儲在 號碼數組:

    NSMutableArray *numbers = [NSMutableArray array]; 
    NSMutableSet *mySet = [NSMutableSet set]; 
    while ([numbers count] < 6) { 
        NSNumber *randNum = @(arc4random_uniform(7) + 1); 
        if (![mySet containsObject:randNum]) { 
         [numbers addObject:randNum]; 
         [mySet addObject:randNum]; 
        } 
    } 
    NSLog(@"numbers: %@", numbers); 
    
  3. 對於一小部分(如7號在你的情況下),你可以簡單地只使用一個數組:

    NSMutableArray *numbers = [NSMutableArray array]; 
    while ([numbers count] < 6) { 
        NSNumber *randNum = @(arc4random_uniform(7) + 1); 
        if (![numbers containsObject:randNum]) { 
         [numbers addObject:randNum]; 
        } 
    } 
    NSLog(@"numbers: %@", numbers); 
    
+0

我喜歡的陣列版本要好很多。謝謝! – user1467534 2014-09-15 17:25:34