2010-11-04 26 views
1

目前,我有一些代碼,看起來像:IPhone SDK:正確的方式返回一個UILabel W/O頁頭

-(UIView)someMethod { 
    CGRectMake(0,0,100,100); 
    UILabel *label = [[UILabel alloc] initWithFrame:rect]; 
    return label; 
} 

雖然工作這顯然出現內存泄漏,需要加以固定。我認爲修復將是:

UILabel *label = [UILabel initWithFrame:rect]; 

但是,編譯器告訴我的UILabel並不initWithFrame迴應。我想我的問題是雙重的:

a)什麼是正確的方法來做到這一點,所以我沒有泄漏內存?

B)我很困惑,爲什麼[的UILabel頁頭]將通過自己initWithFrame迴應,但不是的UILabel(我的理解是的UILabel從UIView的繼承,它響應initWithFrame)。

回答

4

a)您無法避免+alloc。但是您可以使用-autorelease放棄所有權。

-(UIView*)someMethod { 
    CGRect rect = CGRectMake(0,0,100,100); 
    UILabel *label = [[[UILabel alloc] initWithFrame:rect] autorelease]; 
    return label; 
} 

b)中+alloc是一個類的方法,和-initWithFrame:是一個實例方法。後者只能在(或以ObjC術語發送) UILabel的實例上調用。然而,符號「UILabel」是一個類,而不是一個實例,所以[UILabel initWithFrame:rect]將無法​​正常工作。同樣,像+alloc這樣的類方法只能在一個類上調用,所以[label alloc]將不起作用。

+0

明白了。謝謝! – John 2010-11-05 15:07:01

+0

但返回類型是(UIView *)和函數返回(UILabel)!!!可能嗎 ? – Maulik 2011-04-27 11:38:20

+0

@Maulik:UILabel是UIView的子類。 – kennytm 2011-04-27 13:28:23

2

也許更像是:

-(UILabel)someMethod { 

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,100,100)]; 
    return [label autorelease]; 
    } 
0

只需使用你原來的方法,並使用

return [label autorelease]; 

代替。

1

一)

-(UIView *)someMethod { 
    return [[[UILabel alloc] initWithFrame:CGRectMake(0,0,100,100)] autorelease]; 
} 

B)你誤解類方法和實例方法之間的區別。

類方法聲明和像這樣使用:

// declaration: notated with + 
+ (NSDocumentController *)sharedDocumentController; 
// usage 
NSDocumentController * thang = [NSDocumentController sharedDocumentController]; 

一個實例方法聲明,像這樣使用:

// declaration: notated with - 
- (id)init; 
// usage: 
// + alloc is a class method 
//  this requests the class (NSObject) to allocate and return a newly allocated NSObject 
// - init is the instance method 
//  this sends a message to the NSObject instance (returned by [NSObject alloc]) 
NSObject * thang = [[NSObject alloc] init]; 
在你的榜樣

alloc返回一個分配的情況下,你然後希望在其上調用適當的init實例方法。

一些類提供便利的構造,這往往返回一個自動釋放的實例:

+ (NSNumber *)numberWithInt:(int)anInt; 

,但它是不是非常常見的以這種方式重複代碼,除非你有先進的主題,如類集羣工作。當然,如果你發現你經常需要一個特定的功能或便利的構造函數,將它添加到接口可能是一個好主意。