プロパティのセッターを上書きする
Hoge.h
@interface Hoge : NSObject
@property (retain, nonatomic) NSString *string;
@property (assign, nonatomic) NSUInteger count;
@property (assign, nonatomic) BOOL flag;
- (void)method;
@end
Hoge.m
#import "Hoge.h"
@interface Hoge()
{
IBOutlet UILabel *textLabel;
}
@end
#pragma mark -
@implementation
@synthesize string = _string; // アンバー+プロパティ名. " = _" を打てば Xcode が補完してくれるはず
@synthesize count = _count;
@synthesize flag = _flag;
- (void)method {}
// セッターの上書き. "- (void)set" を打てば Xcode が補完してくれるはず
- (void)setString:(NSString*)string
{
// プロパティ属性 retain なので、その処理を自分で書く必要がある
if (_string != string)
{
[_string release]; _string = nil;
_string = [string retain];
}
// セッターで行いたい好きな処理. たとえば UILabel に値を入れる、など
textLabel.text = string;
}
- (void)setCount:(NSUInteger)count
{
_count = count;
// セッターで行いたい好きな処理.
// ……
}
- (void)setFlag:(BOOL)flag
{
_flag = flag;
// セッターで行いたい好きな処理.
// ……
}
// あとしまつ
- (void)dealloc
{
self.string = nil;
[super dealloc];
}
@end
readonlyプロパティの書き方
Hoge.h
@interface Hoge : NSObject
// 公開用プロパティ. readonly なので外部からは読めるが書き換えられない
@property (retain, readonly, nonatomic) NSString *string;
@property (assign, readonly, nonatomic) NSUInteger count;
@property (assign, readonly, nonatomic) BOOL flag;
- (void)method;
@end
Hoge.m
#import "Hoge.h"
@interface Hoge()
// クラス内用プロパティ. readwrite にすることで内部からは普通のプロパティとして扱える
@property (retain, readwrite, nonatomic) NSString *string;
@property (assign, readwrite, nonatomic) NSUInteger count;
@property (assign, readwrite, nonatomic) BOOL flag;
@end
#pragma mark -
@implementation
@synthesize string;
@synthesize count;
@synthesize flag;
- (void)method
{
self.string = @"Hello";
self.count = 100;
self.flag = YES;
}
// あとしまつ
- (void)dealloc
{
self.string = nil;
[super dealloc];
}
@end
Class.m
- (void)hogehoge
{
Hoge *obj = [[[Hoge alloc] init] autorelease];
[obj method];
NSLog(@"%@", obj.string);
NSLog(@"%d", obj.count);
NSLog(@"%d", obj.flag);
}