【问题标题】:setting delegate of WCSession to nil将 WCSession 的委托设置为 nil
【发布时间】:2019-07-29 15:12:01
【问题描述】:

我正在使用“WCSession”来连接我的应用程序和 Apple Watch。我更喜欢单例方法。所以,我做了一个共享会话:

static Shared_WCSession *sharedInstance = nil;
+(Shared_WCSession*)getSharedInstance {
    @synchronized(self) {
        // If the class variable holding the reference to the single ContentManager object is empty create it.
        if(sharedInstance == nil) {
             sharedInstance = [[Shared_WCSession alloc] init];
        }
    }
     return sharedInstance;
}

然后在开始会话中,我为会话设置代理:

-(void)startSession {
     if ([WCSession isSupported]) {
        self.session = [WCSession defaultSession];
        self.session.delegate = self;
        [self.session activateSession];
        LOG(@"WCSession is supported");
    }
}

解除分配委托的正确方法是什么?

根据apple's docs我可以通过以下方法实现:

sessionDidBecomeInactive(_:) 
sessionDidDeactivate(_:)

如果我将委托设置为 nil,这会影响我的应用程序的性能吗?

【问题讨论】:

    标签: ios objective-c apple-watch watchos wcsession


    【解决方案1】:

    首先我想知道 self.session 是跟随 arc 的,并且由于委托总是包含弱引用,所以不需要将其设置为 nil。

    它会导致任何问题吗?如果你没有手动设置它 nil ?如果是,那么您可以在sessionDidDeactivate 中将其设置为零,因为它说:Called after all data from the previous session has been delivered and communication with the Apple Watch has ended. 并且您可以设置新会话,如

    func sessionDidDeactivate(session: WCSession) {
        // Begin the activation process for the new Apple Watch.
        WCSession.defaultSession().activateSession()
    }
    

    【讨论】:

    • 是的,我正在使用 ARC。但是这个委托有两个问题:首先它会导致内存泄漏。其次,有时我的会议管理不顺利。就像我有 2 个苹果手表一样,第二个似乎已连接,但它没有收到任何数据。
    • @taratandel,我想你得到了答案 :) 正如我在回答中提到的那样,弱参考对你有用,就像@property (nonatomic, weak, nullable) id <WCSessionDelegate> delegate;
    【解决方案2】:

    WCSession.delegate 不会泄露:it is a weak reference

    NS_CLASS_AVAILABLE_IOS(9.0)
    @interface WCSession : NSObject
    // ...
    /** A delegate must exist before the session will allow sends. */
    @property (nonatomic, weak, nullable) id <WCSessionDelegate> delegate;
    // ...
    

    如果您使用 ARC 并且您的委托仍被保留在内存中,那不是因为 WCSession.delegate

    【讨论】:

      猜你喜欢
      • 2011-09-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-09
      • 1970-01-01
      • 1970-01-01
      • 2010-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多