LoginSignup
4
3

More than 5 years have passed since last update.

Objective-C property, synthesize Accessor Method の復習

Last updated at Posted at 2014-05-06

理解に間違いがないか再度復習をしてみた

@property@synthesize Accessor Method について

example.h
@interface Example : NSObject

/*
Interface に @property を追加することで、implementation section に instance variable を宣言する必要がなくなる
また、コンパイラーが自動で、implementation section に *x*, *y*, *setX*, *setY* をジェネレートしてくれる
*/

@property int x, y;

- (void)print;

@end
example.m
#import "example.h"

@implementation Example

/*
implementation に 以下のように @sythesize を追加すると instance variable x と y と統合してくれる
@synthesize を指定しないで @property のみを interface に追加すると
_x と _y の instance value を生成をする
*/

@sythesize x, y;

- (void)print {
    // @synthesize がない場合、以下のようになる
    // NSLog(@"_x==%i, _y==%i", _x, _y);
    // self.x = 1; と x = 1; 違いは、self.x と時、Accessor method が動くので、thread safe になる
    NSLog(@"x==%i, y==%i", x, y);
}

@end

Dot Operator を使って Property にアクセスする

Dot Operator は property にアクセスするときのみ利用する。methond の実行などには当然使わない
@synthesize を使って、accessor method と統合する時、"new, alloc, copy, init" で始まる名前を property に指定してはいけない
@synthesize は省くと、(_) アンダースコアーで始まる insatance variable をコンパイラーが自動で名付けする

...
Example *instance = [[Examaple alloc] init];

// 以下、二行は同等
instance.property = 1; 
[instance setProperty:1];

 余談 (id) variable には dot operator は使えない。

4
3
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
4
3