自动生成的主键

时间:2015-06-13 12:33:41

标签: ios

我正在开发一个IOS应用程序。使用核心数据存储数据。但主键自动生成。数据可以存储ID。

//Code Is

NSManagedObjectContext *context = [self managedObjectContext];
    NSManagedObject *userobj = [NSEntityDescription insertNewObjectForEntityForName:@"DetailSave" inManagedObjectContext:context];

    [userobj setValue:[NSNumber numberWithInteger:_userObj.userId] forKey:@"id"];
    [userobj setValue:_titleLabel.text forKey:@"title"];
    NSInteger valInt = 1;
    NSNumber *val = [NSNumber numberWithInteger:valInt];
    [userobj setValue:val forKey:@"quantity"];

    NSString *maxpurch = [dict objectForKey:@"_max_purchases_per_user"];
    NSNumber *maxval = [NSNumber numberWithInteger:[maxpurch integerValue]];
    [userobj setValue:maxval forKey:@"max_purch"];

    NSString *maxPurch = [dict objectForKey:@"_max_purchases"];
    NSNumber *max = [NSNumber numberWithInteger:[maxPurch integerValue]];
    [userobj setValue:max forKey:@"available"];

    NSString *baseprice = [dict objectForKey:@"_base_price"];
    NSNumber *basePrice = [NSNumber numberWithInteger:[baseprice integerValue]];
    [userobj setValue:basePrice forKey:@"amount"];

    //NSLog(@"%@",userobj);
       NSLog(@"app dir: %@",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]);

    NSError *error = nil;
    if (![context save:&error]) {
        NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
    }

    NSFetchRequest *request = [[NSFetchRequest alloc] init];       // Count Entity
    [request setEntity:[NSEntityDescription entityForName:@"DetailSave" inManagedObjectContext:context]];
    [request setIncludesSubentities:NO];
    NSError *err;
    NSUInteger count = [context countForFetchRequest:request error:&err];
    if(count == NSNotFound) {

    }

1 个答案:

答案 0 :(得分:0)

如果M = 8,或者即使M接近8(例如9或10),那么这需要一段时间,你可以更聪明。

-(NSMutableArray *)getEightRandomLessThan:(int)M {
  NSMutableArray *listOfNumbers = [[NSMutableArray alloc] init];
  for (int i=0 ; i<M ; ++i) {
    [listOfNumbers addObject:[NSNumber numberWithInt:i]]; // ADD 1 TO GET NUMBERS BETWEEN 1 AND M RATHER THAN 0 and M-1
  }
  NSMutableArray *uniqueNumbers = [[[NSMutableArray alloc] init] autorelease];
  int r;
  while ([uniqueNumbers count] < 8) {
    r = arc4random() % [listOfNumbers count];
    if (![uniqueNumbers containsObject:[listOfNumbers objectAtIndex:r]]) {
      [uniqueNumbers addObject:[listOfNumbers objectAtIndex:r]];
    }
  }
  [listOfNumbers release];
  return uniqueNumbers;
}

OR

unsigned int permuteQPR(unsigned int x)
{
    static const unsigned int prime = 4294967291;
    if (x >= prime)
        return x;  // The 5 integers out of range are mapped to themselves.
    unsigned int residue = ((unsigned long long) x * x) % prime;
    return (x <= prime / 2) ? residue : prime - residue;
}