如何在Swift里用UnsafeMutablePointer

下午在适配iPadUI的时候,用到了UIPopoverPresentationController,然后在转屏的时候需要调用UIPopoverPresentationControllerDelegate来返回一个适配后的view和CGRect,这里先看下在OC里的写法:
- (void)popoverPresentationController: (nonnull UIPopoverPresentationController *) popoverPresentationController willRepositionPopoverToRect:(inout nonnull CGRect *)rect inView:(inout UIView *__autoreleasing __nonnull * __nonnull)view {
*view = self.someView;
*rect = self.someView.bounds;
}

在OC里面你可以很方便的修改这里的参数值来返回正确的指针地址,但是在swift里面方法是这样子的:

func popoverPresentationController( popoverPresentationController:UIPopoverPresentationController, willRepositionPopoverToRect rect: UnsafeMutablePointer<CGRect>, inView view: AutoreleasingUnsafeMutablePointer<UIView?>) {
     // What to do here?
}

UnsafeMutablePointer和AutoreleasingUnsafeMutablePointer是什么鬼?这俩玩意要怎么返回值给他们?
先说结论
   在Swift里面rect.memory就是Objective-C里面的*rect

原因:

这两个参数并不是swift本身的写法混乱,而是为了让swift和Cocoa和UIKit下的Objective-C和C的frameworks 相互转换兼容,查阅apple的SDK你可以发现UnsafeMutablePointer就是一个结构体:

struct UnsafeMutablePointer<Memory>

你可以把它看成一个Memory的指针,那现在再来看protocol里面的两个参数:

  • UnsafeMutablePointer<CGRect>是一个CGRect的指针
  • AutoreleasingUnsafeMutablePointer<UIView?>是一个可选View的指针

所以这里你可以通过它的memory属性来访问它的引用存储值:

/// Access the underlying raw memory, getting and setting 
values.public var memory: Memory { get nonmutating set }

例如:

// Objective-C assuming 
CGRect *rect;
CGRect oldRect = *rect;
*rect = newRect;

// Swift assuming 
rect: UnsafeMutablePointer<CGRect>
oldRect = rect.memory
rect.memory = newRect

简单来说:在Swift里面rect.memory就是Objective-C里面的*rect
所以最后我们可以在Swift里面这么写:

func popoverPresentationController( popoverPresentationController:UIPopoverPresentationController, willRepositionPopoverToRect rect: UnsafeMutablePointer<CGRect>, inView view: AutoreleasingUnsafeMutablePointer<UIView?>) { 
    view.memory = someView 
    rect.memory = someView.bounds
}

参考:
Swift Standard Library Reference - UnsafeMutablePointer Structure Reference
How to Dereference an Unsafe Mutable Pointer in Swift

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,225评论 4 61
  • 章节导航:Swift开发指南:使用Swift与Cocoa和Objective-C(Swift 4) - 1.入门S...
    Minecode阅读 8,443评论 0 23
  • 还没选好合适的字帖练习,先自己写一篇,只希望在休息之余能够使看到的人身心放松。从不介意点赞的太多哦~
    alien的小雨伞阅读 975评论 0 0
  • 风吹云散船微漾,日落灯初上。 幽林倦鸟一声啼,惹得无端思绪入心扉。 十年客路风尘面,化作声声叹。 月明潮起是他乡,...
    当初不该下凡阅读 2,790评论 4 6
  • 绿豆生北国, 秋发无数枝。 愿君多采撷, 此物最败火。
    玉雕阅读 1,800评论 0 0