Add safeArrayWithObjects class method for safely generating arrays with fields that might be nil.

This commit is contained in:
Hedden, Kyle Matthew 2019-11-27 14:39:43 -05:00 committed by Pfeil, Scott Robert
parent d5823d4368
commit dadbdbfd31
2 changed files with 18 additions and 0 deletions

View File

@ -12,6 +12,9 @@
@interface NSArray (MFConvenience)
/// Creates an array with the given objects, ignoring any nil values, terminated by [NSNull null].
+ (nonnull NSArray *)safeArrayWithObjects:(nullable id)object, ...;
// Gets the object from the array and verfies that it is of a given type.
- (nullable id)objectAtIndex:(NSUInteger)index ofType:(nonnull Class)type;

View File

@ -10,6 +10,21 @@
@implementation NSArray (MFConvenience)
+ (NSArray *)safeArrayWithObjects:(id)object, ... {
NSMutableArray *array = [[NSMutableArray alloc] init];
va_list args;
va_start(args, object);
id nextObject = object;
while(nextObject != [NSNull null]) {
if (nextObject != nil) {
[array addObject:nextObject];
}
nextObject = va_arg(args, id);
}
va_end(args);
return array;
}
- (nullable id)objectAtIndex:(NSUInteger)index ofType:(nonnull Class)type {
id theObject = nil;