Question

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.

Was it helpful?

Solution 3

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];

OTHER TIPS

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;
}

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top