转自:txx's blog
- - (void)someMethod
- {
- NSString *aString = @"loremipsum";
- // This will complain: "Comparison of distinct pointer types ('NSString *' and 'NSNull *')"
- if (aString != [NSNull null])
- {
- }
- // This works (at least for strings), but isEqual: does different things
- // for different classes, so it's not ideal
- if ([aString isEqual:[NSNull null]])
- {
- }
- // If you cast it to the class you're comparing against
- // then you're good to go
- if (aString != (NSString *)[NSNull null])
- {
- }
- // But we can also just cast it to id and
- // that works generically
- if (aString != (id)[NSNull null])
- {
- }
- // The thing that would be really cool,
- // would be [NSNull null] returning
- // id (like in the sample category below).
- // Wouldn't count on that one though.
- if (aString != [NSNull idNull])
- {
- }
- }
- @interface NSNull (idNull)
- + (id)idNull;
- @end
- @implementation NSNull (idNull)
- + (id)idNull { return [NSNull null]; }
- @end
- if ([[NSNull null] isEqual:aString])
- {
- }
- #define NSNullObjects @[@"",@0,@{},@[]]
- @interface NSNull (InternalNullExtention)
- @end
- @implementation NSNull (InternalNullExtention)
- - (NSMethodSignature*)methodSignatureForSelector:(SEL)selector
- {
- NSMethodSignature* signature = [super methodSignatureForSelector:selector];
- if (!signature) {
- for (NSObject *object in NSNullObjects) {
- signature = [object methodSignatureForSelector:selector];
- if (signature) {
- break;
- }
- }
- }
- return signature;
- }
- - (void)forwardInvocation:(NSInvocation *)anInvocation
- {
- SEL aSelector = [anInvocation selector];
- for (NSObject *object in NSNullObjects) {
- if ([object respondsToSelector:aSelector]) {
- [anInvocation invokeWithTarget:object];
- return;
- }
- }
- [self doesNotRecognizeSelector:aSelector];
- }
- @end
- #import "NSNull+OVNatural.h"
- @implementation NSNull (OVNatural)
- - (void)forwardInvocation:(NSInvocation *)invocation
- {
- if ([self respondsToSelector:[invocation selector]]) {
- [invocation invokeWithTarget:self];
- }
- }
- - (NSMethodSignature *)methodSignatureForSelector:(SEL)selector
- {
- NSMethodSignature *sig = [[NSNull class] instanceMethodSignatureForSelector:selector];
- if(sig == nil) {
- sig = [NSMethodSignature signatureWithObjCTypes:"@^v^c"];
- }
- return sig;
- }
- @end