为什么我刚刚创建的指针抛出了KERN_INVALID_ADDRESS?

时间:2017-01-25 14:37:05

标签: ios objective-c swift

因此,与此recently posted question类似,我在将Amazon的AWS Obj-C库与我的Swift应用程序集成时遇到问题。我有NSOperation使用Transfer Utility library处理文件上传到S3,其中包括对后台文件传输的支持。在最近发布我们的应用程序后,我一直看到代码中的一些崩溃,当应用程序返回到前台时,它会重新启动进度处理程序。代码改编自their Obj-C example

- (void)viewDidLoad {
    [super viewDidLoad];

    ...

    AWSS3TransferUtility *transferUtility = [AWSS3TransferUtility defaultS3TransferUtility];
    [transferUtility
     enumerateToAssignBlocksForUploadTask:^(AWSS3TransferUtilityUploadTask *uploadTask, __autoreleasing AWSS3TransferUtilityUploadProgressBlock *uploadProgressBlockReference, __autoreleasing AWSS3TransferUtilityUploadCompletionHandlerBlock *completionHandlerReference) {
         NSLog(@"%lu", (unsigned long)uploadTask.taskIdentifier);

         // Use `uploadTask.taskIdentifier` to determine what blocks to assign.

         *uploadProgressBlockReference = // Reassign your progress feedback block.
         *completionHandlerReference = // Reassign your completion handler.
     }
     downloadTask:^(AWSS3TransferUtilityDownloadTask *downloadTask, __autoreleasing AWSS3TransferUtilityDownloadProgressBlock *downloadProgressBlockReference, __autoreleasing AWSS3TransferUtilityDownloadCompletionHandlerBlock *completionHandlerReference) {
         NSLog(@"%lu", (unsigned long)downloadTask.taskIdentifier);

         // Use `downloadTask.taskIdentifier` to determine what blocks to assign.

         *downloadProgressBlockReference =  // Reassign your progress feedback block.
         *completionHandlerReference = // Reassign your completion handler.
     }];
}

到我的Swift版本,在尝试取消引用EXC_BAD_ACCESS KERN_INVALID_ADDRESS时与newProgressPointer崩溃:

// Swift 2.3

class AttachmentQueue: NSOperationQueue {

    ...

    /**
     Recreates `UploadOperation` instances for any that were backgrounded by the user leaving the
     app.
     */
    func addBackgroundedOperations() {
        let transferUtility = AWSS3TransferUtility.defaultS3TransferUtility()
        transferUtility.enumerateToAssignBlocksForUploadTask({ (task, progress, completion) -> Void in
            guard let operation = UploadOperation(task: task, oldProgressPointer: progress, oldCompletionPointer: completion) else { return }
            self.addOperation(operation)
        }, downloadTask: nil)
    }

}
 /// An `UploadOperation` is an `NSOperation` that is responsible for uploading an attachment asset
 /// file (photo or video) to Amazon S3. It leans on `AWSS3TransferUtility` to get the actual
 /// uploading done.
 class UploadOperation: AttachmentOperation {

    ...

    /// An `AutoreleasingUnsafeMutablePointer` to the upload progress handler block.
    typealias UploadProgressPointer = AutoreleasingUnsafeMutablePointer<(@convention(block) (AWSS3TransferUtilityTask, NSProgress) -> Void)?>

    /// An `AutoreleasingUnsafeMutablePointer` to the upload completion handler block.
    typealias UploadCompletionPointer = AutoreleasingUnsafeMutablePointer<(@convention(block) (AWSS3TransferUtilityUploadTask, NSError?) -> Void)?>


     /**
      A convenience initializer to be used to re-constitute an `AWSS3TransferUtility` upload task that
      has been moved to the background. It should be called from `.enumerateToAssignBlocksForUploadTask()`
      when the app comes back to the foreground and is responsible for re-hooking-up its progress and
      completion handlers.

      - parameter task:                 The `AWSS3TransferUtilityTask` that needs re-hooking-up.
      - parameter oldProgressPointer:   An `AutoreleasingUnsafeMutablePointer` to the original progress handler.
      - parameter oldCompletionPointer: An `AutoreleasingUnsafeMutablePointer` to the original completion handler.
      */
     convenience init?(task: AWSS3TransferUtilityUploadTask, oldProgressPointer: UploadProgressPointer, oldCompletionPointer: UploadCompletionPointer) {

         self.init(attachment: nil) // Actual implementation finds attachment record

         // Re-connect progress handler
         var progressBlock: AWSS3TransferUtilityProgressBlock = self.uploadProgressHandler
         let newProgressPointer = UploadProgressPointer(&progressBlock)
         print("newProgressPointer", newProgressPointer)
         print("newProgressPointer.memory", newProgressPointer.memory) // Throws EXC_BAD_ACCESS KERN_INVALID_ADDRESS
         oldProgressPointer.memory = newProgressPointer.memory

         // Re-connect completion handler
         var completionBlock: AWSS3TransferUtilityUploadCompletionHandlerBlock = self.uploadCompletionHandler
         let newCompletionPointer = UploadCompletionPointer(&completionBlock)
         oldCompletionPointer.memory = newCompletionPointer.memory
     }

     /**
      Handles file upload progress. `AWSS3TransferUtility` calls this repeatedly while the file is
      uploading.

      - parameter task:     The `AWSS3TransferUtilityTask` for the current upload.
      - parameter progress: The `NSProgress` object for the current upload.
      */
     private func uploadProgressHandler(task: AWSS3TransferUtilityTask, progress: NSProgress) {

         // We copy the `completedUnitCount` to operation but it would be nicer if we could just
         // reference the one passed to us instead of having two separate instances
         self.progress.completedUnitCount = progress.completedUnitCount

         // Calculate file transfer rate using an exponential moving average, as per https://stackoverflow.com/a/3841706/171144
         let lastRate = self.transferRate
         let averageRate = Double(progress.completedUnitCount) / (NSDate.timeIntervalSinceReferenceDate() - self.uploadStartedAt!)
         self.transferRate = self.smoothingFactor * lastRate + (1 - self.smoothingFactor) * averageRate;
         progress.setUserInfoObject(self.transferRate, forKey: NSProgressThroughputKey)
     }

     /**
      Handles file upload completion. `AWSS3TransferUtility` calls this when the file has finished
      uploading or is aborted due to an error.

      - parameter task:  The `AWSS3TransferUtilityTask` for the current upload.
      - parameter error: An instance of `NSError` if the upload failed.
      */
     private func uploadCompletionHandler(task: AWSS3TransferUtilityUploadTask, error: NSError?) {

        ...

     }

     ...

 }

为什么指针memory在创建后会直接引用无效?

对iOS开发不熟悉且没有使用Obj-C(或其他非内存管理语言)的实际经验,我有点迷失。如果有人能够提供一些非常感激的亮点。

修改

enumerateToAssignBlocksForUploadTask(…)

的Swift方法签名
/**
 Assigns progress feedback and completion handler blocks. This method should be called when the app was suspended while the transfer is still happening.

 @param uploadBlocksAssigner   The block for assigning the upload pregree feedback and completion handler blocks.
 @param downloadBlocksAssigner The block for assigning the download pregree feedback and completion handler blocks.
 */
public func enumerateToAssignBlocksForUploadTask(uploadBlocksAssigner: ((AWSS3TransferUtilityUploadTask, AutoreleasingUnsafeMutablePointer<(@convention(block) (AWSS3TransferUtilityTask, NSProgress) -> Void)?>, AutoreleasingUnsafeMutablePointer<(@convention(block) (AWSS3TransferUtilityUploadTask, NSError?) -> Void)?>) -> Void)?, downloadTask downloadBlocksAssigner: ((AWSS3TransferUtilityDownloadTask, AutoreleasingUnsafeMutablePointer<(@convention(block) (AWSS3TransferUtilityTask, NSProgress) -> Void)?>, AutoreleasingUnsafeMutablePointer<(@convention(block) (AWSS3TransferUtilityDownloadTask, NSURL?, NSData?, NSError?) -> Void)?>) -> Void)?)

1 个答案:

答案 0 :(得分:1)

我认为你不应该需要大多数(或任何)这些指针。看看Swift example code from AWS,看看它是否没有找到您正在寻找的内容。

按照你的方式创建指针在Swift中是不安全的。这可能是你所需要的更多信息(你不应该努力工作),但这里可能会发生什么(这种解释在这种情况下并不完全正确,但它和#39;可能发生的事情,因此值得了解):

  • 您创建一个指向本地(堆栈)变量progressBlock
  • 的指针
  • 系统发现progressBlock不再在范围内的任何其他位置访问。
  • 如果允许这样做,ARC会摧毁progressBlock
  • 您不安全地访问指向已销毁变量的指针,然后崩溃。

我说这感觉不对,因为对闭包的第二个引用应该保持闭包活着,但通常用这种方式用构造函数创建指针是非常危险的。 / p>

(这可能会导致崩溃,因为您无法print @convention(block)关闭;我从未尝试过这样做。它不是尝试打印非常正常。)

无论如何,如果你确实需要做这种事情(我认为你不是这样),你需要按照以下方式去做:

withUnsafeMutablePointer(to: self.uploadProgressHandler) { newProgressPointer in 
    ... newProgressPointer is safe to use in this block ...
}

但是作为一项规则,如果您要转换ObjC代码(不是纯C,而只是ObjC),并且发现您需要创建大量Unsafe个对象,那么您可能会走错了路。大多数ObjC事物都与Swift很好地联系Unsafe

相关问题