Objective-Cでメンバ変数を宣言する場合、ヘッダファイルに @propertyを記述し、実装ファイルに @synthesize宣言を入れるのが一般的ですが、実装ファイルに @propertyを宣言するだけでも問題ないようです。この方がシンプルに記述でき、機密性も保たれるのと、setter/getterの役割も兼ねてくれるので良いですね。
以下にサンプルを作成しました。
サンプルダウンロード
ソースコード
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
| #import "ViewController.h"
@interface ViewController ()
@property NSString *sampleStr;
@property int sampleInt;
@property BOOL sampleBool;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self main];
[self debugStr];
[self debugInt];
[self debugBool];
}
- (void)main
{
_sampleStr = @"サンプル";
_sampleInt = 777;
_sampleBool = YES;
}
- (void)debugStr
{
NSLog(@"_sampleStr: %@", _sampleStr);
NSLog(@"self.sampleStr: %@", self.sampleStr);
NSLog(@"[self sampleStr]: %@", [self sampleStr]);
}
- (void)debugInt
{
NSLog(@"_sampleInt: %d", _sampleInt);
NSLog(@"self.sampleInt: %d", self.sampleInt);
NSLog(@"[self sampleInt]: %d", [self sampleInt]);
}
- (void)debugBool
{
NSLog(@"_sampleBool: %d", _sampleBool);
NSLog(@"self.sampleBool: %d", self.sampleBool);
NSLog(@"[self sampleBool]: %d", [self sampleBool]);
}
@end
|
出力結果
サンプル
777
YES
参考サイト
Modern Objective-Cでのシンプルなプロパティ記述方式
お薦めの参考書
絶対に挫折しない iPhoneアプリ開発「超」入門 増補改訂第4版
Swiftについて知りたい開発者の方のみならず、プログラミング未経験者の方にも参考になる内容になっています。Swiftの基礎を一から丁寧に解説されており、この書籍があればネットで調べる手間をかなり省くことができると思います。