【Objective-C】外部からは読み取りだけ、内部クラスでは読み書き可能のプロパティ宣言の書き方【Xcode10.2対応】
こういう人に向けて発信しています。
・hファイルとクラスエクステンションに同一変数名でプロパティ宣言したい人
・クラスエクステンションについて理解したい人
・Objective-C中級者
*********SecondViewController.h*********
#import <UIKit/UIKit.h>
@interface SecondViewController : UIViewController
@property (readonly) NSString *readString; //外部から読み取りのみ
@end
*********SecondViewController.m*********
#import "SecondViewController.h"
///クラスエクステンション
@interface SecondViewController ()
@property (readwrite) NSString *readString; ///クラス内部では読み書き可能。
///@property (readonly) NSString *readString; と書くと不要なプロパティ宣言の完全重複なので怒られる。
@end
@implementation SecondViewController
- (void)viewDidLoad {
[super viewDidLoad];
_readString = @"a";
}
@end
上記のようにヘッダーファイルでは外部公開のプロパティを宣言し、
クラス内部でしかアクセス出来ないクラスエクステンション部分に、
readwriteで宣言してあげればいいです。
どういう挙動になるんか。
外部からSecondViewControllerのインスタンスを取得して、
readStringプロパティの値を更新しようとエラーになります。
readonlyだからですね。
ですが、SecondViewControllerではviewDidLoadで実行できているように
読み書きができます。
この記事が気に入ったらサポートをしてみませんか?