[英]In Objective-c how do I make a method that's accessible by all child class, but not accessible publicly
[英]How do I make an allocator class method in Objective-C?
我有一個有酒吧屬性的NSFoo類。 我想有一個類方法來獲取一個帶有bar屬性集的NSFoo實例。 這與NSString stringWithFormat類方法類似。 簽名將是:
+ (NSFoo *) fooWithBar:(NSString *)theBar;
所以我會這樣稱呼它:
NSFoo *foo = [NSFoo fooWithBar: @"bar"];
我認為這可能是正確的:
+ (NSFoo *) fooWithBar:(NSString *)theBar {
NSFoo *foo = [[NSFoo alloc] init];
foo.bar = theBar;
[foo autorelease];
return foo;
}
那看起來不錯嗎?
是。 看起來不錯。 你的實現似乎是一種常見的做法。
是的,您的實施看起來正確。 因為-[NSObject autorelease]
返回self
,你可以將return語句寫為return [foo autorelease]
。 如果您打算使用自動釋放(而不是發布),有些人建議在分配時自動釋放對象,因為它使意圖清晰並將所有內存管理代碼保存在一個位置。 您的方法可以寫成:
+ (NSFoo *) fooWithBar:(NSString *)theBar {
NSFoo *foo = [[[NSFoo alloc] init] autorelease];
foo.bar = theBar;
return foo;
}
當然,如果-[NSFoo initWithBar:]
存在,您可能會將此方法編寫為
+ (NSFoo *) fooWithBar:(NSString *)theBar {
NSFoo *foo = [[[NSFoo alloc] initWithBar:theBar] autorelease];
return foo;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.