LoginSignup
11
10

More than 5 years have passed since last update.

NSCopying サンプル

Last updated at Posted at 2014-06-13
import Foundation

class Product : NSObject, NSCopying {
    var _type: String

    init(_ type: String) {
        _type = type
    }

    func copyWithZone(zone: NSZone) -> AnyObject! {
        var newInstance = Product(_type)
        return newInstance
    }
}

var foo = Product("test")
var bar = foo.copy() as Product

if (foo === bar) {
    println("reference")
} else {
    println("copy") // copy
}

概要

  • コピー機能を実装するクラスが NSObject NSCopying を継承していること
  • コピー機能を実装するクラスに copyWithZone メソッドを実装すること
  • コピー先の変数に代入する際、copy() メソッドを呼び、as クラス名 を最後に付与すること (付けなくても動作するが、Variable 'bar' inferred to have type 'AnyObject!', which may be unexpected と warning が出る)

P.S.

@NSCopying については期待する動作にならないので追って調査

ref https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/Attributes.html

11
10
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
11
10