Skip to content

Instantly share code, notes, and snippets.

@iyuuya
Created August 1, 2012 22:34
Show Gist options
  • Save iyuuya/3231301 to your computer and use it in GitHub Desktop.
Save iyuuya/3231301 to your computer and use it in GitHub Desktop.
Objective-C における @Property@synthesize の簡単な説明
// ------------------------------------------------------------------------ //
#pragma mark - 定義ファイル側
@interface SomeClass : NSObject
{
// ここにメンバ変数を定義できるが、しなくてもよい
// (@synthesize 時に実体となる変数を定義できるため)
NSObject *_apple; // メンバ変数 _apple を定義しておく (後の例示の為)
}
/*
@property は規則付きの getter, setter を生成するための定義
ただし getter, setter だけではなく、メンバ変数ごと定義することもできる (最新のランタイムの場合)
@property には属性を設定することが可能で、それにより振る舞いが変わる
@property は実装側で @synthesize しなければいけない
(いけないということはないけど、最初はそう思っていてもよい)
*-----------------------------------------------------------------
| 指定できる属性(ARC無効時):
| retain assign copy
| (参照カウントを操作する) or (参照カウントを操作しない) or (複製が保持される)
*-----------------------------------------------------------------
| 指定できる属性(ARC有効時):
| strong weak copy
| (強い参照を持つ) or (弱い参照を持つ) or (複製が保持される)
| (ARC無効時のプロパティも使用可能)
*-----------------------------------------------------------------
| 指定できる属性(共通):
| atomic nonatomic
| (スレッドセーフである) or (スレッドセーフでない)
|
| readonly readwrite
| (getterのみ作られる) or (getter, setterが作られる)
デフォルトは atomic, assign(weak), readwrite
*/
@property (nonatomic, strong) NSObject *apple;
@property (nonatomic, strong) NSObject *orange;
@property (nonatomic, strong) NSObject *lemon;
@property (nonatomic, strong) NSObject *melon;
- (void)someMethod;
@end
// ------------------------------------------------------------------------ //
#pragma mark - 実装ファイル側
@implementation SomeClass
// プロパティとメンバ変数を synthesize(合成) する
// プロパティ = メンバ変数
@synthesize apple = _apple; // 既に定義されているメンバ変数を指定
@synthesize orange = _orange; // 新しくメンバ変数を定義して指定
@synthesize lemon = neko; // 実体を指すメンバ変数の名前に決まりはない
@synthesize melon; // 実体を省略すると同名のメンバ変数が指定されたことになる
- (void)someMethod
{
// setter は全部使える
self.apple = [[NSObject alloc] init];
self.orange = [[NSObject alloc] init];
self.lemon = [[NSObject alloc] init];
self.melon = [[NSObject alloc] init];
// 実体の中に全部ちゃんと入る
NSLog(@"apple: %@", _apple);
NSLog(@"orange: %@", _orange);
NSLog(@"lemon: %@", neko);
NSLog(@"melon: %@", melon);
// getter を介しても同じ結果になる
NSLog(@"apple: %@", self.apple);
NSLog(@"orange: %@", self.orange);
NSLog(@"lemon: %@", self.lemon);
NSLog(@"melon: %@", self.melon);
// 一番上と同じ処理をブラケット記法で書いた場合
[self setApple: [[NSObject alloc] init]];
[self setOrange:[[NSObject alloc] init]];
[self setLemon: [[NSObject alloc] init]];
[self setMelon: [[NSObject alloc] init]];
// ちゃんと更新されてる
NSLog(@"apple: %@", self.apple);
NSLog(@"orange: %@", self.orange);
NSLog(@"lemon: %@", self.lemon);
NSLog(@"melon: %@", self.melon);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment