17
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UUIDをなるべく短い文字列に変換する

Last updated at Posted at 2014-08-28

Objective-CではNSUUIDでUUIDを生成できますが、これを文字列で保存あるいは送信する必要がある場合、通常はUUIDStringメソッドを用いて、1799AE5A-2F5D-4E89-B709-3B45AF6FE58Fのような形式の36文字を得ることになると思います。区切り文字を除いても32文字です。

これより短い文字列表現が欲しい場合、Base64を使う方法があります。この場合は24文字、パディング文字を除けば22文字で済みます。

以下にNSUUIDのカテゴリとしての実装例を示します。文字列表現におけるパディングの有無を引数で指定するようになっています。

NSUUID+Base64.h
//
//  NSUUID+Base64.h
//
//
 
#import <Foundation/Foundation.h>
 
@interface NSUUID (Base64)
 
- (instancetype)initWithBase64String:(NSString*)string withPadding:(BOOL)padding;
- (NSString*)Base64StringWithPadding:(BOOL)padding;
 
@end
NSUUID+Base64.m
//
//  NSUUID+Base64.m
//
//
 
#import "NSUUID+Base64.h"
 
@implementation NSUUID (Base64)
 
- (instancetype)initWithBase64String:(NSString*)string withPadding:(BOOL)padding
{
    if (padding == NO) {
        string = [string stringByPaddingToLength:(string.length + (string.length % 4)) withString:@"=" startingAtIndex:0];
    }
 
    NSData* d = [[NSData alloc] initWithBase64EncodedString:string options:NSDataBase64DecodingIgnoreUnknownCharacters];
    uuid_t bytes;
    [d getBytes:bytes];
    return [self initWithUUIDBytes:bytes];
}
 
- (NSString*)Base64StringWithPadding:(BOOL)padding
{
    uuid_t bytes;
    [self getUUIDBytes:bytes];
    NSString* string = [[NSData dataWithBytes:bytes length:sizeof(uuid_t)]
                        base64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength];
    if (padding == NO) {
        return [string stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"="]];
    } else {
        return string;
    }
}
 
@end
17
18
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?