IOS中的四種變量修飾關鍵字 @private @protected @public @package

文檔上記錄是這樣的html

The Scope of Instance Variablesios

To enforce the ability of an object to hide its data, the compiler limits the scope of instance variables—that is, limits their visibility within the program. app

爲了強制一個對象隱藏其數據,編譯器限制實例變量範圍以限制其在程序中的可見性框架

But to provide flexibility, it also lets you explicitly set the scope at four levels. Each level is marked by a compiler directive:ide

可是爲了提供靈活性,蘋果也讓開發者顯式設置範圍(四選一)函數

Directiveflex

Meaningui

@privatespa

The instance variable is accessible only within the class that declares it.rest

@protected

實例變量只能被聲明它的類訪問

The instance variable is accessible within the class that declares it and within classes that inherit it. All instance variables without an explicit scope directive have@protectedscope.

實例變量能被聲明它的類和子類訪問,全部沒有顯式制定範圍的實例變量都是@protected


@public

The instance variable is accessible everywhere.

實例變量能夠被在任何地方訪問。


@package

Using the modern runtime, an@packageinstance variable has@publicscope inside the executable p_w_picpath that implements the class, but acts like@privateoutside.使用modern運行時,一個@package實例變量在實現這個類的可執行文件鏡像中其實是@public的,可是在外面就是@private【runtime須要再看一下蘋果文檔Runtime Programming Guide

The@packagescope for Objective-C instance variables is analogous toprivate_externfor C variables and functions. Any code outside the class implementation’s p_w_picpath that tries to use the instance variable gets a link error.

Objective-C中的@package與C語言中變量和函數的private_extern相似。任何在實現類的鏡像以外的代碼想使用這個實例變量都會引起link error

This scope is most useful for instance variables in framework classes, where@privatemay be too restrictive but@protectedor@publictoo permissive.

這個類型最經常使用於框架類的實例變量,使用@private太限制,使用@protected或者@public又太開放

相關文章
相關標籤/搜索