2010-05-27 52 views
0

我很好奇,如果有一個很好的理由,我應該/不應該在下面的tabBarController中使用@synthesize,或者沒有關係?@synthesize與UITabBarController?

@implementation ScramAppDelegate 
@synthesize window; 
@synthesize tabBarController; 

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  
    [self setTabBarController:[[UITabBarController alloc] init]]; 
    [window addSubview:[tabBarController view]]; 
    [window makeKeyAndVisible]; 
    return YES; 
} 

-(void)dealloc { 
    [tabBarController release]; 
    [self setTabBarController: nil]; 
    [window release]; 
    [super dealloc]; 
} 

OR

@implementation ScramAppDelegate 
@synthesize window; 

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  
    tabBarController = [[UITabBarController alloc] init]; 
    [window addSubview:[tabBarController view]]; 
    [window makeKeyAndVisible]; 
    return YES; 
} 

-(void)dealloc { 
    [tabBarController release]; 
    [window release]; 
    [super dealloc]; 
} 

歡呼加里

回答

1

我個人不打擾@property我的視圖控制器在我的應用程序委託類。主要是因爲應用程序委託位於視圖層次結構的頂部,並且它不需要將其成員變量公開給任何人。

另一個原因不是來自行:

tabBarController = [[UITabBarController alloc] init]; 

因爲如果tabBarController@property設置爲retain,你會雙保留對象,它是內存泄漏的一種形式(雖然相對溫和因爲它發生在應用程序委託級別)。

+0

我一直在想內存泄漏,這就是爲什麼我做了[tabBarController release];和[self setTabBarController:nil];在dealloc中。通過我的思維方式,導致正確的內存管理,雖然它稍微有些學術性,但dealloc從不會被調用,因爲應用程序在退出時可以釋放所有內存。 – fuzzygoat 2010-05-30 19:25:12

+0

問題在於你已經保留了兩次('alloc'遞增了保留計數,然後你的屬性被設置爲'retain',所以生成的setter會再次增加這個計數),所以如果你'重新釋放一次,然後將其設置爲零,您將創建一個內存泄漏。 – 2010-05-30 19:43:55

+0

所以保留計數是2,在釋放它的1之後,設置nil之後它再次釋放(現在它的0)並且保留nil? – fuzzygoat 2010-05-30 19:55:43

-1

如果tabBarController是一個屬性(與@property (nonatomic, retain) TabBarController *tabBarController您的.h文件中聲明),並且要爲它自動創建getter和setter方法,你應該在你的.m文件中使用@synthesize。如果你想自己實現getter和setter,你必須指定@dynamic tabBarController

+0

如果您沒有使用@synthesize _而且您沒有立即實現您自己的getter和setter,則只需要使用@dynamic指令,例如,如果Core Data將爲您創建建模屬性。如果.m文件包含具有適當名稱和類型的getter和setter,則不需要使用@synthesize或@dynamic。 – 2010-08-05 04:04:20