簡體   English   中英

Objective-C類別將AppDelegate作為屬性返回

[英]Objective-C Category Return AppDelegate as property

我正在UIViewController類上創建一個Objective-C類別。 在我的項目中,我想要一種簡單易行的方法來獲取應用程序委托。

這就是我在做什么

// header file UIViewController+AppDelgate.h
#import <UIKit/UIKit.h>

@class ExampleAppDelegate;

@interface UIViewController (AppDelegate)
@property (weak, nonatomic, readonly) ExampleAppDelegate *appDelegate;
@end

// implementation file UIViewController+AppDelegate.m
#import "UIViewController+AppDelegate.h"
#import "ExampleAppDelegate.h"

@implementation UIViewController (AppDelegate)

- (ExampleAppDelegate *) appDelegate {
    return (ExampleAppDelegate *)[[UIApplication sharedApplication] delegate];
}

@end

我應該將屬性定義為弱嗎? 我認為留住這個家伙是不好的,因為通常保留在其中引用的視圖控制器上。

在這種情況下,弱/強是有爭議的,因為沒有本地實例變量保存指針。 ARC將做正確的事情(即,對於任何給定范圍,它發送的保留數量不會超過發布的數量)。

為什么不使用具有相同功能的類方法創建Utility類,那么您可以引用以下內容:

[Utility appDelegate];

而且您不必向需要訪問AppDelegate的每個ViewController添加屬性,就如同您當前對其進行設置的方式一樣。

從實現的外觀上,您不需要定義屬性,只需要聲明方法-(ExampleAppDelegate *)appDelegate;

當然,除非在類的實例上調用,否則除非您將其設置為類方法,否則這僅會起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM