16
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

addSubViewした時の参照?weakプロパティの謎

Last updated at Posted at 2013-01-17

なんかよくわからくなった。初心者的な話なのかも。Twitterで質問したら、優しい人が何人かリプライを飛ばしてくれたのですが、ながすぎて、返信しきれないので、ここに書いてみます。

まずこのコードは正しい

.m
UIImage *image = [UIImage imageNamed:@"sample"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[self.view addSubview:imageView];

これで、self.viewにstrong参照になり、もちろんsample画像が表示される。

参考(http://blog.natsuapps.com/2011/11/ios5-arc-weakproperty-for-outle.html)

これは表示されない

さて、上記のimageViewをpropertyで持ちたい。addSubviewすると、strongで参照されるので、weakで持つのがいいよね。だって、removeFromSuperviewされたときは開放したいじゃん?(ですよね?不安)

.h
@property (weak, nonatomic) UIImageView *imageView;
.m
UIImage *image = [UIImage imageNamed:@"sample"];
self.imageView = [[UIImageView alloc] initWithImage:image];
[self.view addSubview:self.imageView];

これ、表示されない。なんで?

これは表示される。当たり前だけど。

.m
UIImage *image = [UIImage imageNamed:@"sample"];
UIImage *imageView = [[UIImageView alloc] initWithImage:imageView];
[self.view addSubview:imageView];
self.imageView = imageView;

こうしなきゃダメなの?

これも表示される

.m
UIImage *image = [UIImage imageNamed:@"sample"];
UIImage *imageView = [[UIImageView alloc] initWithImage:imageView];
self.imageView = imageView;
[self.view addSubview:self.imageView];

これは大丈夫。

結局どういうことなのか

わからん。こういうのってどうやって調べるんだろう。もしなぜかのか知ってたら教えて下さい。お願いします。

weak参照のsetterがなんか悪さしてそう??

答えを教えて頂きました

ローカル変数(この場合はimageView)も強参照だからという話じゃないですかね。弱参照だけになった瞬間にオブジェクトはreleaseされるので、self.imageViewプロパティはその時点でnullになるはず。岡田哲哉さん (@t_okada)

とのこと。確かにそうだ!

16
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?