質問

iPadゲームを開発しています。私はこのことに遭遇します。これは私のサンプルコードです:

方法1:

Foo.h

@interface Foo : UIView{
    UILabel *title;
    .... // Other objects like UISlider, UIbuttons, etc.
}

// I add @property for all the objects.
@property (nonatomic, retain) UILabel *title;

... blablabla

Foo.m
// I synthesize all the properties.
@synthesize title;
... blablabla

// Release in dealloc method
[title release];
....
[super dealloc];

方法2:

Foo.h

@interface Foo : UIView{
    UILabel *title;
    .... // Others object like UISlider, UIbuttons, etc.
}
// But this time I didn't add @property, synthesize and release.

Foo.m
// When I need the label, I allocate it:
title = [[UILabel alloc] initWithRect: CGRect(10, 10, 100, 30)];
title.text = @"test";
[self addSubview: title];
[title release];

メソッド1と2の両方が機能しますが、2つのメソッドの違いは何ですか(Method2のコードが少ない)?

どの方法を使用する必要があり、その理由は何ですか?

それはメモリ管理と関係がありますか?

役に立ちましたか?

解決

メソッド2は、送信することから技術的に正しくありません -release タイトルを得るために、あなたはもうそれに興味がないことを示します。すぐにゼロにする必要があります。

方法1は絶対に問題あり、その外側にある利点があります -dealloc あなたが常にそれを参照するためにプロパティを使用した場合、あなたは取得することを心配する必要はありません -retain-release -右。

他のヒント

違いは、方法2では、Fooオブジェクトの外側からタイトルにアクセスできないことです。インスタンス変数はクラスのプライベートです。

また、アロック/保持とリリースのバランスをとる必要があります。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top