2009-08-01 4 views
0

(私たちはカスタムUIViewControllerのサブクラスの中のコードについて話しています - そして、私はIBを使いません) - (void)loadView、次にコントロールとビューを作成し、 - (void)viewDidLoadを作成し、それらをサブビューに追加します。コントロールがメンバーでない場合、私はそれを作成し、この方法でそれをローカルにリリースする場合、これは私がそれを行う方法です:私が作成しただろうかのほんの一例ザッツ(UILabel付)iPhone Dev - メンバーがサブビューとして追加されるべき方法

- (void)viewDidLoad { 
    UILabel *localLabel = [[UILabel alloc] initWithFrame:CGRectMake(81, 384, 148, 21)]; 
    localLabel.text = @"I'm a Label!"; 
    localLabel.AutoresizingMask = (UIViewAutoresizingFlexibleLeftMargin | 
            UIViewAutoresizingFlexibleRightMargin | 
            UIViewAutoresizingFlexibleBottomMargin); 

    [self.view addSubview:localLabel]; 
    [localLabel release]; 
    [super viewDidLoad]; 
} 

プロパティを設定し、サブビューに追加してリリースします。しかしメンバーで、私はこれを実行します。

UILabel *lblMessage; 
... 
@property (nonatomic, retain)UILabel *lblMessage; 
... 
- (void)viewDidLoad { 
    UILabel *localMessage = [[UILabel alloc] initWithFrame:CGRectMake(81, 384, 148, 21)]; 
    localMessage.text = @"I'm a Label!"; 
    localMessage.AutoresizingMask = (UIViewAutoresizingFlexibleLeftMargin | 
             UIViewAutoresizingFlexibleRightMargin | 
             UIViewAutoresizingFlexibleBottomMargin); 
    self.lblMessage = localMessage; 
    [localMessage release]; 

    [self.view addSubview:lblMessage]; 
    [super viewDidLoad]; 
} 

をしかし、私はまた、それが私の始めてiPhone 3開発中のものと同様

... 
- (void)viewDidLoad { 
    UILabel *localMessage = [[UILabel alloc] initWithFrame:CGRectMake(81, 384, 148, 21)]; 
    localMessage.text = @"I'm a Label!"; 
    localMessage.AutoresizingMask = (UIViewAutoresizingFlexibleLeftMargin | 
             UIViewAutoresizingFlexibleRightMargin | 
             UIViewAutoresizingFlexibleBottomMargin); 
    self.lblMessage = localMessage; 

    [self.view addSubview:localMessage]; 
    [localMessage release]; 
    [super viewDidLoad]; 
} 

を行って見てきました:SDKの本を模索します。ローカル変数を追加してから解放します。私はどちらをすべきですか?それはまったく重要ですか?

答えて

1

lblMessageが保持プロパティ(しばしば真である)である場合、機能的な違いはありません。それ以外の場合は、release-before-addSubviewはバグで、解放されたオブジェクトをサブビューとして追加しようとします。ここで

は、プロパティlblMessageが保持されると仮定すると、localMessageの参照カウントの迅速なリハーサルです:

UILabel *localMessage = [[UILabel alloc]... // retainCount is now 1 
// Set up localMessage. If you release'd now, you'd dealloc the object. 
self.lblMessage = localMessage; // retainCount is now 2 
// You can safely call release now if you'd like. 
[self.view addSubview:localMessage]; // retainCount is now 3. 
[localMessage release]; // retainCount is now 2. 

あなたが効果的にそのオブジェクトへの2つの参照持っているので、あなたは、retainCountが2で終了したい - あなたのメンバーをポインタlblMessageと、別の保持ポインタself.viewにあります。

0

メンバであるラベルとローカルスコープのラベルは、同じオブジェクトになるように互いに参照されているので、どちらの方法でも問題はありません。ローカルを持たず、ラベルを直接初期化します

+0

lblMessageは保持プロパティなので、ローカルなものを作成する必要があるので、self.lblMessage = [[UILabel alloc] initWithFrame:..]; objリファレンス2を作成します。 – mk12

+0

Ur文は正確ではなく、countwillはまだI Bliveです – Daniel

関連する問題