1

I am developing one iOS application using storyboard and core data. For my application I need to generate one random string like 'M000142140502343524' which are not already exist in the 'data' field of the 'tableA' when click a button.

Cœur
  • 37,241
  • 25
  • 195
  • 267
user3564078
  • 61
  • 1
  • 6
  • 1
    How much like that string? Could it be a UUID string, for example? – Droppy May 02 '14 at 09:11
  • check this ->http://stackoverflow.com/questions/2633801/generate-a-random-alphanumeric-string-in-cocoa – Mohit May 02 '14 at 09:12
  • M000142140502343524 this is the one string already in the data field of the tableA.Like this string more than 30000 strings are already saved in the data field.I need to generate on random string in each click a button.But the conditions are it is something similar to the strings in the data filed but not exactly similar because the data field is unique. – user3564078 May 02 '14 at 09:14
  • You can use the timestamp that will be unique at a time – Sunny Shah May 02 '14 at 09:16

3 Answers3

11

Common way to generate an unique string is

NSString *UUID = [[NSUUID UUID] UUIDString];

or

NSString *identifier = [[NSProcessInfo processInfo] globallyUniqueString];

But you also could create such string yourself. For example:

+ (NSString *)createRandomName
{
    NSTimeInterval timeStamp = [ [ NSDate date ] timeIntervalSince1970 ];
    NSString *randomName = [ NSString stringWithFormat:@"M%f", timeStamp];
    randomName = [ randomName stringByReplacingOccurrencesOfString:@"." withString:@"" ];
    return randomName;
}
Avt
  • 16,927
  • 4
  • 52
  • 72
2

You can generate a unique identifier (UUID) like this:

NSString *randomUUIDString = [[NSUUID UUID] UUIDString];

aslı
  • 8,740
  • 10
  • 59
  • 80
1

This will generate the random key

   NSTimeInterval  today = [[NSDate date] timeIntervalSince1970];
    NSString *intervalString = [NSString stringWithFormat:@"%f", today];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[intervalString doubleValue]];

    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyyMMddhhmm"];
    NSString *strdate=[formatter stringFromDate:date];
Sunny Shah
  • 12,990
  • 9
  • 50
  • 86
  • M000 + random string here i need the random string in based today...yyyymmddhhmmss....like 20140502034855....2014 year...05 month...02 day....03 hour....48minutes...55 seconds(current time..) – user3564078 May 02 '14 at 10:20
  • Thank you Sunny Shah.It's working.I will mark your answer as correct answer. – user3564078 May 02 '14 at 11:37