LoginSignup
24
22

More than 5 years have passed since last update.

NSDataとは

Last updated at Posted at 2015-04-04

NSDataとは

バイトデータのラッパークラス

NSData and its mutable subclass NSMutableData provide data objects, object-oriented wrappers for byte buffers.

NSData Class Reference

NSDataは何ができるか

Data objects can manage the allocation and deallocation of byte buffers automatically. Among other things, data objects can be stored in collections, written to property lists, saved to files, and transmitted over communication ports.

Introduction to Binary Data Programming Guide for Cocoa

Snippet

データの長さを取得

let url = NSURL(string: "https://www.google.com/images/srpr/logo11w.png")
let data = NSData(contentsOfURL: url!)
print(data!.length)

データをbase64 encodeした文字列に変換する

let url = NSURL(string: "https://www.google.com/images/srpr/logo11w.png")
let data = NSData(contentsOfURL: url!)
//64文字毎に改行を入れるオプション
let base64EncodedString64Char = data!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
//76文字毎に改行を入れるオプション
let base64EncodedString76Char = data!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding76CharacterLineLength)

base64EncodedStringWithOptions呼び出し時にLineEncodingのオプションを指定しない場合はCRLFが付与される

If you specify one of the line length options (NSDataBase64Encoding64CharacterLineLength or NSDataBase64Encoding76CharacterLineLength) but don’t specify the kind of line ending to insert, the default line ending is Carriage Return + Line Feed.

base64 encodeされたデータをデコードする

let url = NSURL(string: "https://www.google.com/images/srpr/logo11w.png")
let data = NSData(contentsOfURL: url!)

let base64EncodedString = data!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)

let decodedData = NSData(base64EncodedString: base64EncodedString, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)

データを部分的に取得する

let url = NSURL(string: "https://www.google.com/images/srpr/logo11w.png")
let data = NSData(contentsOfURL: url!)
let first10Byte = data!.subdataWithRange(NSMakeRange(0, 10))

データをファイルに保存する

let url = NSURL(string: "https://www.google.com/images/srpr/logo11w.png")
let data = NSData(contentsOfURL: url!)
data?.writeToFile("./logo.png", atomically: true)

NSString<=>NSData間の変換

let orig_str = "string"

//String -> NSData
let data = orig_str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)

//NSData -> String
let str = NSString(data: data!, encoding: NSUTF8StringEncoding)

String Encodings - NSString

24
22
0

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
24
22