まずモデルから実装する。
モデルクラス - SelectionHistory
前回定義した仕様でモデルに関係するところをピックアップすると次の通り。
- 範囲選択でキャプチャ実行した時の位置と大きさを履歴として記録する
- 同じ大きさが履歴にある場合は位置のみ更新する(常に履歴内のすべてのサイズは異なる)
- 過去の履歴は最大10件までとする
- 履歴は次回起動時にも利用できる
- 履歴件数はプリファレンスで変更できる
- 履歴はプリファレンスで削除できる
モデルはこのロジックを実装すればいい。
こんな感じで書いてみた。
インターフェイス
@interface SelectionHistory : NSObject {
NSMutableArray* historyArray_;
}
+ (SelectionHistory*)sharedSelectionHistory;
- (void)addHistoryRect:(NSRect)frame;
- (NSArray*)array;
- (NSRect)rectAtIndex:(int)index;
- (void)clearAll;
@endシングルトンとして実装し +shareSelectionHistory でインスタンスを取得する。
static SelectionHistory* selectionHistory_;
+ (SelectionHistory*)sharedSelectionHistory
{
if (selectionHistory_ == nil) {
selectionHistory_ = [[SelectionHistory alloc] init];
}
return selectionHistory_;
}NSRect を受け取り追加する。
- (void)addHistoryRect:(NSRect)rect
{
NSInteger index;
for (index=0; index < [historyArray_ count]; index++) {
NSValue* historyValue = [historyArray_ objectAtIndex:index];
NSRect historyRect = [historyValue rectValue];
if (NSEqualSizes(historyRect.size, rect.size)) {
break;
}
}
if (index < [historyArray_ count]) {
// found it
[historyArray_ removeObjectAtIndex:index];
}
[historyArray_ addObject:[NSValue valueWithRect:rect]];
while ([historyArray_ count] >
[[UserDefaults valueForKey:UDKEY_SELECTION_HISTORY_MAX] intValue]) {
[historyArray_ removeObjectAtIndex:0];
}
[self save];
}追加にあたっては履歴中に同じサイズのものがある場合には、それを削除し新たに追加しなおす。つまり同サイズは最近のものだけを残すようにする。また履歴の最大数を越えた場合は履歴の数を調整する。追加の最後に NSUserDefaults へ保存する。
- (void)save
{
NSMutableArray* rectArray = [NSMutableArray array];
for (NSValue* rectValue in historyArray_) {
NSString* rectString = NSStringFromRect([rectValue rectValue]);
[rectArray addObject:rectString];
}
[UserDefaults setValue:rectArray forKey:UDKEY_SELECTION_HISTORY];
[UserDefaults save];
}キャプチャ時に履歴追加
モデルができたのでキャプチャ時に記録するようコードを追加した。
:
case TAG_RECORD:
[_capture_controller setContinouslyFlag:NO];
[_capture_controller saveImage:[self capture] imageFrame:_rect];
[[SelectionHistory sharedSelectionHistory] addHistoryRect:_rect];
[_capture_controller exit];
break;
:試しに実行して試してみよう。履歴の中身をデバッグコンソールへ出力した。
NSRect: {{155, 180}, {400, 250}}
NSRect: {{155, 180}, {298, 343}}
NSRect: {{776, 71}, {210, 128}}よさそうだ。
- - - -
次回は表示。



Responses
Leave a Response