Porting rails' .blank? to Objective C
I have to write some iOS software again and therefore I had the desire to have something like Rails' .blank?
method. It checks for numbers if they're zero, for strings if they are empty or only consist of whitespaces and for arrays/hashes if they have no values.
This can easily be created via a category to NSObject
in Objective-C:
// IsEmpty.h
#import <Foundation/Foundation.h>
@interface NSObject (IsEmpty)
- (BOOL) isEmpty; @end
// IsEmpty.m
#import "IsEmpty.h"
@implementation NSObject (IsEmpty)
-
(BOOL) isEmpty { if([self isKindOfClass:[NSString class]]) { return [[(NSString *)self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0; } else if([self isKindOfClass:[NSNumber class]]) { return [(NSNumber *)self floatValue] == 0; }
return self == nil || ([self respondsToSelector:@selector(length)] && [(NSData *)self length] == 0) || ([self respondsToSelector:@selector(count)] && [(NSArray *)self count] == 0); }
@end