Differences between [NSArray arrayWithArray:] and [NSArray copy]

前端 未结 7 2042
清歌不尽
清歌不尽 2021-02-12 13:50

lately I work much with arrays and I\'m wonder.. what\'s diffrences between those two lines.

NSArray *array = [NSArray arrayWithArray:someArray];
相关标签:
7条回答
  • 2021-02-12 14:27

    In Swift, it's very different. Thanks to the new open-source Foundation for Swift, we know that whereas init(array:) creates a new array with the items given (if any), copy() simply returns self.

        public override func copy() -> AnyObject {
            return copyWithZone(nil)
        }
    
        public func copyWithZone(zone: NSZone) -> AnyObject {
            return self
        }
    

    https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/NSArray.swift#L82

        public convenience init(array: [AnyObject]) {
            self.init(array: array, copyItems: false)
        }
    
        public convenience init(array: [AnyObject], copyItems: Bool) {
            let optionalArray : [AnyObject?] =
                copyItems ?
                    array.map { return Optional<AnyObject>(($0 as! NSObject).copy()) } :
                    array.map { return Optional<AnyObject>($0) }
    
            // This would have been nice, but "initializer delegation cannot be nested in another expression"
    //        optionalArray.withUnsafeBufferPointer { ptr in
    //            self.init(objects: ptr.baseAddress, count: array.count)
    //        }
            let cnt = array.count
            let buffer = UnsafeMutablePointer<AnyObject?>.alloc(cnt)
            buffer.initializeFrom(optionalArray)
            self.init(objects: buffer, count: cnt)
            buffer.destroy(cnt)
            buffer.dealloc(cnt)
        }
    

    https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/NSArray.swift#L116

    So, obviously, copy() is faster, and now you know how they both work! (Just only in Swift)

    0 讨论(0)
提交回复
热议问题