19
A
回答
15
從技術上講,沒有。屬性實際上只是方法,所有方法都是公共的。 Objective-C中「保護」方法的方式是不讓其他人知道它們。
實際上,是的。您可以在類擴展中定義屬性,並且仍然可以在主實現塊中使用這些屬性。
0
你可以在子類實現中使用這樣的語法。
@interface SuperClass (Internal)
@property (retain, nonatomic) NSString *protectedString;
@end
9
這可以通過使用包含在基類和子類的實現文件中的類擴展(不是類別)來實現。
甲類擴展定義類似於類,但沒有類別名稱:
@interface MyClass()
在一類擴展,可以聲明屬性,這將能夠合成所述背襯的ivars(的XCode> 4.4自動合成的ivars也適用於此)。
在擴展類中,您可以覆蓋/細化屬性(只讀更改爲readwrite等),並添加對實現文件「可見」的屬性和方法(但請注意屬性和方法不是非常私人,仍然可以通過選擇器調用)。
其他人提出了利用此一個單獨的頭文件MyClass_protected.h,但是這也可以使用#ifdef
這樣的主頭文件來完成:
例子:
BaseClass.h
@interface BaseClass : NSObject
// foo is readonly for consumers of the class
@property (nonatomic, readonly) NSString *foo;
@end
#ifdef BaseClass_protected
// this is the class extension, where you define
// the "protected" properties and methods of the class
@interface BaseClass()
// foo is now readwrite
@property (nonatomic, readwrite) NSString *foo;
// bar is visible to implementation of subclasses
@property (nonatomic, readwrite) int bar;
-(void)baz;
@end
#endif
BaseClass.m
// this will import BaseClass.h
// with BaseClass_protected defined,
// so it will also get the protected class extension
#define BaseClass_protected
#import "BaseClass.h"
@implementation BaseClass
-(void)baz {
self.foo = @"test";
self.bar = 123;
}
@end
ChildClass.h
// this will import BaseClass.h without the class extension
#import "BaseClass.h"
@interface ChildClass : BaseClass
-(void)test;
@end
ChildClass.m
// this will implicitly import BaseClass.h from ChildClass.h,
// with BaseClass_protected defined,
// so it will also get the protected class extension
#define BaseClass_protected
#import "ChildClass.h"
@implementation ChildClass
-(void)test {
self.foo = @"test";
self.bar = 123;
[self baz];
}
@end
當你調用#import
,它基本上是複製粘貼.h文件到您導入它。 如果你有一個#ifdef
,它將只包含裏面的代碼,如果#define
這個名字被設置。
在你的.h文件中,你不要設置定義,所以導入這個.h的任何類都不會看到受保護的類的擴展。 在基類和子類.m文件中,在使用#import
之前使用#define
,以便編譯器將包含受保護的類擴展。
相關問題
- 1. 使用CSS僅基於其可見性屬性設置類的css屬性
- 2. .index()僅適用於類
- 3. CSS屬性不適用於主體類
- 4. 僅檢索子類的屬性
- 5. 關於驗證類及其集合屬性的建議
- 6. 接口及其子類及其類型和子類型的泛型迭代器
- 7. 將屬性添加到UIViewController及其所有子類
- 8. 獲得屬性值屬於其他類
- 9. 如何使基類方法的屬性適用於繼承類?
- 10. Log4j適用於一個類,不適用於其他類
- 11. 用戶定義的運行時屬性僅適用於自定義類嗎?
- 12. 爲什麼託管屬性只適用於類屬性,而不適用於python中的實例屬性?
- 13. 用於對象及其屬性?
- 14. 僅適用於超類的NHibernate QueryOver
- 15. 子類的屬性
- 16. 屬性的子類
- 17. 多態參數適用於超類,但不適用於子類
- 18. CGPoint屬性用於從其他類與左值錯誤的類
- 19. 將基類型的屬性應用於JavaScript中的子類型
- 20. Python類屬性和子類
- 21. 良好的性能僅適用於一類樸素貝葉斯
- 22. DataAnnotations僅適用於EntityFramework/Linq2Sql類嗎?
- 23. GetElementBy僅適用於ID不適用於類
- 24. C#屬性及其用法
- 25. 用於常規屬性類
- 26. 僅適用於非固有類的類的只讀版本
- 27. java get屬性只存在於子類
- 28. wordpress next_post_link()僅適用於當前子類別
- 29. Opencart - 如何僅顯示產品類別及其子產品?
- 30. 如何使用類別向NSObject添加屬性,以及NSObject的所有子類
要被「保護」,類擴展接口需要位於一個單獨的頭文件中,以包含在類及其子類中。 – JeremyP 2010-11-24 09:37:18
據我所知,任何在基類接口擴展中聲明的屬性都不可用於子類 - 它們的作用域是私有的,不受保護。看到這個SO討論:http://stackoverflow.com/questions/5588799/objective-c-how-do-you-access-parent-properties-from-subclasses – memmons 2011-04-08 00:06:05