0

(カスタムUIViewControllerサブクラス内のコードについて話しています-ちなみに、IBは使用していません)わかりました。self.viewメンバーを-(void)loadViewに設定してから、コントロールやビューなどを作成します。 in-(void)viewDidLoadをクリックし、サブビューに追加します。コントロールがメンバーでない場合、それを作成してメソッドでローカルにリリースすると、次のようになります:( UILabelを使用)

- (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];
}

しかし、私もそれが行われているのを見ました

...
- (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];
}

私の最初のiPhone3開発では、そのように:SDKブックを探索します。ローカル変数を追加してから解放することに注意してください。どちらをすればいいですか?それはまったく重要ですか?

4

2 に答える 2

1

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

プロパティが保持されてlocalMessageいると仮定して、の参照カウントの簡単なウォークスルーを次に示します。lblMessage

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で終了する必要があります。lblMessageself.view

于 2009-08-01T22:00:24.003 に答える
0

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

于 2009-08-01T21:57:38.767 に答える