iPhone Dev-メンバーをサブビューとして追加する方法
-
10-07-2019 - |
質問
(カスタムUIViewControllerサブクラス内のコードについて話している-そして、私はIBを使用しない方法で)OKですので、self.viewメンバーを-(void)loadViewに設定してから、コントロールを作成し、ビューと何でも-(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];
}
iPhone 3の開発を始めたときのように:SDKブックを探索します。ローカル変数を追加してから解放します。どっちがいい?どうでもいいですか?
解決
lblMessage
が保持プロパティである場合(多くの場合true)、機能的な違いはありません。それ以外の場合、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.
retainCount
を2で終了する必要があります。これは、そのオブジェクトへの2つの参照(メンバーポインター lblMessage
、および self .view
。
他のヒント
メンバーであるラベルとローカルスコープラベルは相互の参照であるため、同じオブジェクトであるため、どの方法を使用してもかまいません。ローカルを持たず、ラベルを直接初期化するだけです