Cocoaのフレームワークの中には簡単な構造体を文字列に変換するのに便利な関数が用意されている。NSLog()などで印字する際に%@では変換できないのでそれを簡易にできるいわばデバッグ用なんだろうと思う。
NSStringFromCGRect, NSStringFromCGPoint, NSStringFromCGSize (NSStringFromNSRect, NSStringFromNSPoint, NSStringFromNSPoint)やNSStringRomRangeがそれ。
だが、NSIndexPathとかよく使う割にそういうのが用意されていない。Objective-Cクラスなので、descriptionメッセージに文字列を返すのでそれで十分ってことなんだろうけど、アドレス情報があったりしてちょっと見にくい。
なので代わりになるメソッドを作ってみた。デバッグ用ということで実効効率はあまり考慮していないが使ってみて欲しい。
ついでに文字列からオブジェクトを作る方も用意した。
section = 1, row = 5なら"1.5"とか{ 1, 5, 6, 4 }なら "1.5.6.4"とかの結果になる。
NSIndexSetもついでにと思ったが、そっちはあまり使っていないので、まあ今度必要になったら作ろうと思う。
@interface NSIndexPath (String)
- (NSString*)stringValue;
+ (NSIndexPath*)indexPathFromString:(NSString*)aString;
@end
@implementation NSIndexPath (String)
- (NSString*)stringValue
{
NSMutableArray *anArray = [NSMutableArray arrayWithCapacity:self.length];
for (NSUInteger pos = 0; pos < self.length; pos++) {
NSUInteger index = [self indexAtPosition:pos];
[anArray addObject:[NSNumber numberWithUnsignedInteger:index]];
}
return [anArray componentsJoinedByString:@"."];
}
+ (NSIndexPath*)indexPathFromString:(NSString*)aString
{
NSArray *anArray = [aString componentsSeparatedByString:@"."];
NSIndexPath *indexPath = [[NSIndexPath alloc] init];
for (NSString *aComponent in anArray) {
NSUInteger index = [aComponent integerValue];
indexPath = [indexPath indexPathByAddingIndex:index];
}
return indexPath;
}
@end
// (C) 2012 Eien Factory
ARC利用前提の実装です。
一応MITライセンスにしますが、改変再配布商用利用自由。