這是Objective-C協議的正確使用嗎? - Is this the proper use of Objective-C protocols? -开发者知识库

這是Objective-C協議的正確使用嗎? - Is this the proper use of Objective-C protocols? -开发者知识库,第1张

I'm building an app with, for the purposes of this question, three custom classes: AppDelegate, ListWindowController and ViewOptionsWindowController. AppDelegate keeps retains properties of the single instances of ListWindowController and ViewOptionsWindowController.

我正在構建一個應用程序,為了這個問題的目的,有三個自定義類:AppDelegate,ListWindowController和ViewOptionsWindowController。 AppDelegate保留了ListWindowController和ViewOptionsWindowController的單個實例的屬性。

When the user selects a particular menu item, an action in AppDelegate is executed that instantiates the ViewOptionsWindowController. Changes made in this controller's window need to be reflected in ListWindowController's window (either adding or removing a column from the window's table view).

當用戶選擇特定菜單項時,執行AppDelegate中的實例,該實例將實例化ViewOptionsWindowController。在此控制器窗口中進行的更改需要反映在ListWindowController的窗口中(從窗口的表視圖中添加或刪除列)。

So, I've defined a protocol, ViewOptionsChanged, which has two required methods, -addColumn and -removeColumn (with parameters to indicate what to add or remove). I've indicated that ListViewController conforms to this protocol, and when instantiating ViewOptionsWindowController am passing AppDelegate's instance of ListViewController. The declaration of ViewOptionsWindowController's init method is:

所以,我已經定義了一個協議ViewOptionsChanged,它有兩個必需的方法-addColumn和-removeColumn(帶有參數來指示要添加或刪除的內容)。我已經指出ListViewController符合這個協議,並在實例化ViewOptionsWindowController時傳遞AppDelegate的ListViewController實例。 ViewOptionsWindowController的init方法的聲明是:

- (id)initWithListController:(id <ViewOptionsChanged>)listController;

so that the only facts that ViewOptionsWindowController knows about the listController parameter is that it conforms to this protocol.

因此,ViewOptionsWindowController了解listController參數的唯一事實是它符合此協議。

So, my question is, is this the proper use of Objective-C protocols? Or would some other design pattern be more appropriate?

所以,我的問題是,這是否正確使用Objective-C協議?或者其他一些設計模式會更合適嗎?

2 个解决方案

#1


2  

Yes .. but I think it is a tad confusing. I'd make listView a proper delegate of viewOptions

是..但我認為這有點令人困惑。我將listView作為viewOptions的正確委托

maybe name the protocol ViewOptionsDelegate and the methods viewOptions:changedTo: and put the logic to add/remove columns in the listController?

也許命名協議ViewOptionsDelegate和方法viewOptions:changedTo:並把邏輯添加/刪除listController中的列?

feels more cocoa like and really logic about columns don't belong with viewOptions.

感覺更像可可,並且關於列的邏輯真的不屬於viewOptions。

but ultimately -- even if you dont agree -- it is used ok IMO.

但最終 - 即使你不同意 - 它也可以用於IMO。

最佳答案:

DABAN RP主题是一个优秀的主题,极致后台体验,无插件,集成会员系统
U19学习网站 » 這是Objective-C協議的正確使用嗎? - Is this the proper use of Objective-C protocols? -开发者知识库