2013-01-03 28 views
13

在Objective-C,它是最好的做法是:在.h接口或.m文件中的擴展中聲明屬性?

  1. 聲明對象如在.H按鈕,然後在.M

    .h 
    @interface SomeViewController : UIViewController 
        @property (strong, nonatomic) UIButton *someButton; 
    @end 
    
    .m 
    @implementation SomeViewController 
        @synthesize someButton = _someButton; 
    @end 
    
  2. 合成或它們聲明爲在高德該.M

    @interface SomeViewController() 
        @property (strong, nonatomic) UIButton *someButton; 
    @end 
    

我注意到,在很多蘋果代碼,具體兵衛r Breadcrumbs示例代碼,其許多屬性在界面中聲明。兩者有什麼不同?我還注意到,當在@interface中聲明屬性時,它們會自動合成一個下劃線前綴,使someButton = _someButton合成無用。

+2

這兩個聲明都是屬性聲明。 ivar由'@ synthesize'創建。它們的功能完全相同;不同的是他們對其他文件的可見性。 –

回答

31

首先,as of Xcode 4.4就不再需要@synthesize(除非你改變這兩個setter和getter方法),要麼當@property@interface@implementation聲明。

如果只從類內訪問@property,則在.m文件中聲明@propertyclass extension。這提供了封裝並使其很容易看到@property未被其他課程使用。

如果@property被其他類使用,按設計,然後在.h文件中的@interface中定義它。

+1

我想評論一下,「很少有必要再使用@ @ synthesize'」。 (在某些情況下,例如Core Data子類的只讀屬性或屬性,實際上仍然需要使用'@ synthesize',因爲Xcode仍然不能很好地理解這些。) –

+0

我完全同意@ JRG-Developer。 – zaph

+0

+1很好的解釋 – Leena

相關問題