2013-04-30 90 views
0

下一個代碼僅適用於LBYouTubePlayerController* controller;@implementation ViewController之內。有人可以向我解釋爲什麼我會得到這種行爲,有什麼區別?只有當我在實現中初始化對象時,代碼纔有效。

.h文件中:

#import <UIKit/UIKit.h> 
#import "LBYouTube.h" 

@interface ViewController : UIViewController<LBYouTubePlayerControllerDelegate> 

@end 

.m文件:

#import "ViewController.h" 

@interface ViewController() 

@end 

@implementation ViewController 
{ 
    LBYouTubePlayerController* controller; 
} 
- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
     controller = [[LBYouTubePlayerController alloc] initWithYouTubeURL:[NSURL URLWithString:@"http://www.youtube.com/watch?v=1UlbCgB9vms"] quality:LBYouTubeVideoQualityLarge]; 
    controller.delegate = self; 
    controller.view.frame = CGRectMake(0.0f, 0.0f, 200.0f, 200.0f); 
    controller.view.center = self.view.center; 
    [self.view addSubview:controller.view]; 

如果我將繼續前進LBYouTubePlayerController* controller;並把它裏面viewDidLoad視頻將不會加載:

- (void)viewDidLoad 
    { 
LBYouTubePlayerController* controller = [[LBYouTubePlayerController alloc] initWithYouTubeURL:[NSURL URLWithString:@"http://www.youtube.com/watch?v=1UlbCgB9vms"] quality:LBYouTubeVideoQualityLarge]; 
    controller.delegate = self; ....} 
+1

你使用ARC嗎?無論哪種方式,您想要引用LBYouTubePlayerController。如果你沒有使用ARC,那麼你的內存泄漏沒有引用,如果使用ARC,實例被解除分配,並且只有視圖處於活動狀態,這意味着LBYouTubePlayerController無法加載視圖,調用方法等。 – TheBlack 2013-04-30 16:41:14

+0

是的,xcode 4.6.2 – Segev 2013-04-30 16:42:11

+0

這實際上是一個奇怪的方式。通常你會有一個視圖控制器,但看起來像你使用兩個。如果你沒有保留屬性引用,LBYouTubePlayerController將被釋放。 – sosborn 2013-04-30 16:44:01

回答

4

在你的工作例如,您使用的是instance variable(伊娃)。在非工作示例中,您使用的是local variable。內存對於這些變量的處理方式不同。 使用Automatic Reference Counting (ARC),塊中聲明和初始化的任何對象將在該塊中最後一次使用該對象後自動釋放(並在此情況下解除分配)。通過聲明一個實例變量,就像在你的工作示例中一樣,你可以防止這種情況發生。一旦擁有的對象(ViewController)本身被釋放,一個ivar就會被釋放。

1

這是實例變量和局部變量之間的區別。谷歌是你研究這個問題的朋友。

對象的生命週期中存在一個實例變量(取決於您如何創建它)。局部變量的持續時間與其範圍相同(在本例中爲您的方法)。

你需要在這裏使用一個實例變量,以便控制器實際上存在足夠長的時間來使用它。雖然你可以像這樣更好地定義你的實例變量:

@interface ViewController() 

@property (strong, nonatomic) LBYouTubePlayerController *controller; 

@end 
+1

請注意,在這種情況下,您必須通過在下劃線前加'_controller'來訪問自動生成的實例變量。或者使用訪問器方法'[self controller]'。或者使用點語法'self.controller'。 – DrummerB 2013-04-30 16:46:40