Skip to content

Instantly share code, notes, and snippets.

@nhnam
Created March 15, 2016 13:52
Show Gist options
  • Save nhnam/89d728bf316adfaf4792 to your computer and use it in GitHub Desktop.
Save nhnam/89d728bf316adfaf4792 to your computer and use it in GitHub Desktop.
//
// NSArray+Safe.h
// NNSafeArray
//
// Created by Nguyen Hoang Nam on 15/3/16.
// Copyright © 2016 Alan Nguyen. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSArray(Safe)
- (void)setObject:(id)obj atIndexedSubscript:(NSUInteger)idx;
- (id)objectAtIndexedSubscript:(NSUInteger)index;
@end
//
// NSArray+Safe.m
// NNSafeArray
//
// Created by Nguyen Hoang Nam on 15/3/16.
// Copyright © 2016 Alan Nguyen. All rights reserved.
//
#import "NSArray+Safe.h"
@implementation NSArray(Safe)
- (id)objectAtIndexedSubscript:(NSUInteger)index {
return [self safeObjectForIndex:index];
}
- (id)safeObjectForIndex:(NSUInteger)index {
if ( index >= self.count) {
return nil;
}
id object = [self objectAtIndex:index];
if ([object isKindOfClass:[NSNull class]] || !object) return nil;
else return object;
}
- (void)setObject:(id)object atIndexedSubscript:(NSUInteger)idx {
if ([object isKindOfClass:[NSNull class]] || !object) {
return;
} else {
self[idx] = object;
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment