Skip to content

Instantly share code, notes, and snippets.

@tondol
Last active December 20, 2015 04:39
Show Gist options
  • Save tondol/6072954 to your computer and use it in GitHub Desktop.
Save tondol/6072954 to your computer and use it in GitHub Desktop.
動的型検査付きNSArray/NSDictionary
//
// NSCollection+TypeSafe.h
//
#import <Foundation/Foundation.h>
#define TYPESAFE_ARRAY(classname) \
@interface NSArray (TypeSafe ## classname) \
- (classname *)get ## classname:(int)index; \
- (classname *)get ## classname:(int)index none:(classname *)none; \
@end \
@implementation NSArray (TypeSafe ## classname) \
- (classname *)get ## classname:(id)index \
{ \
return [self get ## classname:index none:nil]; \
} \
- (classname *)get ## classname:(int)index none:(classname *)none \
{ \
NSObject *object = [self objectAtIndex:index]; \
if ([object isKindOfClass:[classname class]]) { \
return object; \
} \
return none; \
} \
@end
#define TYPESAFE_DICTIONARY(classname) \
@interface NSDictionary (TypeSafe ## classname) \
- (classname *)get ## classname:(id)key; \
- (classname *)get ## classname:(id)key none:(classname *)none; \
@end \
@implementation NSDictionary (TypeSafe ## classname) \
- (classname *)get ## classname:(id)key \
{ \
return [self get ## classname:key none:nil]; \
} \
- (classname *)get ## classname:(id)key none:(classname *)none \
{ \
classname *object = [self objectForKey:key]; \
if ([object isKindOfClass:[classname class]]) { \
return object; \
} \
return none; \
} \
@end
// 使い方のサンプル
#import "NSCollection+TypeSafe.h"
TYPESAFE_ARRAY(NSString)
TYPESAFE_ARRAY(NSNumber)
@interface Hoge : NSObject
@end
@implementation Hoge
- (void)hoge
{
NSArray *array = [NSArray arrayWithObjects:@"a", @"b", @"c", nil];
NSLog(@"0: %@", [array getNSString:0]); // => a
NSLog(@"1: %@", [array getNSNumber:1]); // => (null)
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment