4
4

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.

改めてObjective-C の言語を理解する(プロパティ編 その2)

Posted at

前回の続きです

前回がsetterオプションでしたので、今回はgetterオプションを確認します。

確認前の予想

setterオプションと同様にgetterメソッドが明示的に指定出来て、全てのアクセスが指定されたgetter経由となると思われる。

オプション(アクセサー名の指定: getter=)

まずは前回同様に、オプションだけ指定して呼び出してみます。
想定では実行時にクラッシュします。

// Person.h
# import <Foundation/Foundation.h>

@interface Person : NSObject

@property (getter=shortName) NSString *name3;

@end
// ViewController.m
# import "ViewController.h"
# import "Person.h"

@interface ViewController ()

@end

@implementation ViewController

// ------ 一部省略 ------ //

# pragma mark -

// プロパティ実験(アクセサー名の指定)
- (IBAction)tapPropertiesTestByAccessorName:(id)sender {
    
    Person *person = [[Person alloc] init];

    // NG: メソッドを用意していないから
    NSString *name = person.shortName;
    NSLog(@"name=%@", name);
}
@end

結果

クラッシュしませんでした。
値も取得出来ています。

調査しました

setterオプションと同じ結果になると予測していたのに、同じ結果にならないのはやはり実際に実行しないとわからないこともあるものだと痛感させられました。
同じ結果にならない理由については、また別途調べたいと思います。

getterオプションについても、メソッドを用意することで必ずそのメソッド経由で取得されるようになるのは確認出来ました。

// Person.m
# import "Person.h"

@implementation Person

-(NSString*)shortName {
    return _name3;
}

@end

備考

思った結果にならないことがあると面白いです。(但し、心にゆとりがあれば)
プロパティだけで意外とボリュームがあるので、真面目に全てを理解してから始める方法と行うと辛いかもしれませんね。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?