2014-03-31 46 views
0

我試圖用Core Data創建一個隨機函數的新程序員。我想要的是標籤從我的實體中返回一個隨機的managedObject。這是我的代碼Core Data Xcode中的隨機函數

- (IBAction)randomize{ 
    NSEntityDescription *entitydesc = [NSEntityDescription entityForName:@"Restraunt" inManagedObjectContext:context ]; 
    NSFetchRequest *request = [[NSFetchRequest alloc]init]; 
    [request setEntity:entitydesc]; 
    NSError *error; 
    NSArray *matchingData = [context executeFetchRequest:request error:&error]; 
    NSString *textString; 
    int RandomNumber; 
    RandomNumber = arc4random() %[matchingData count]; 
    textString = [matchingData objectAtIndex:RandomNumber]; 
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"restraunt_name like %@",textString]; 
    [request setPredicate:predicate]; 

    if(matchingData.count <= 0){ 
     self.label.text = @"doesnt exist";} 
    else { 
     NSString *string; 
     for (NSString *obj in matchingData){ 
      string = [obj valueForKey:@"restraunt_name"]; 

     } 
     self.label.text = [NSString stringWithFormat:@" %@", string] ; 
    } 
} 
+1

你看到了什麼?你期望看到什麼? – Abizern

+0

我希望看到字符串,但我看到在內存中的位置 – user3481875

回答

0

這段代碼有幾個錯誤。例如,「textString」不是一個字符串,它是你的一個Restraunt實體。而且,你在else子句中的for循環只是循環遍歷所有實體(使得你的隨機選擇不相關),所以「string」將是數據中的最後一個餐廳名稱。你的代碼應該是這個樣子,

- (IBAction)randomize{ 
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Restraunt"]; 
    NSError *error; 
    NSArray *matchingData = [context executeFetchRequest:request error:&error]; 
    int randomNumber = arc4random() %[matchingData count]; 
    NSManagedObject *aRestraunt = matchingData[randomNumber]; // aRestraunt might not be an NSManagedObject depending on whether you've subclassed NSManagedObject or not -- if you have, then that should probably be Restraunt instead. 

    self.label.text = [aRestaurant valueForKey:@"restraunt_name"]; 
} 

編輯後:

我上面提供的答案基本上是「修復了」您的代碼,使其工作。但是,這不是獲得單個隨機對象的最有效方法。沒有必要把所有的對象都拿到內存中去獲得一個。相反,你可以得到您的記錄算作哈爾穆勒在他的評論中提出,然後用fetchOffset結合的fetchLimit得到一條記錄,

NSError *error; 
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Restraunt"]; 
NSUInteger count = [context countForFetchRequest:request error:&error]; 
if (! error) { 
    NSUInteger rand = arc4random_uniform() % count; 
    [request setFetchOffset:rand]; 
    [request setFetchLimit:1]; 
    NSError *fetchError; 
    NSManagedObject *aRestraunt = [[context executeFetchRequest:request error:&fetchError] lastObject]; 
    if (! fetchError) { 
     self.label.text = [aRestaurant valueForKey:@"restraunt_name"]; 
    }else{ 
     NSLog(@"There was an error in fetching a Restraunt entity"); 
} 
+0

Ohhhhh好吧,我看你做了什麼;我當時的想法太複雜了。非常感謝你 – user3481875

+0

不使用調用結果和錯誤參數。我很失望。你真的應該使用arc4random_uniform() – Abizern

+0

而不是實例化存儲中的每個'@「Restraunt」'實體,'NSUInteger'recordCount = [context countForFetchRequest:request error:&error];如果(recordCount!= NSNotFound){...' –