RoLYroLLs
RoLYroLLs

Reputation: 3215

NSString: Return value or Empty string

I've been looking at a several Google search results and have found various ways to test an NSString for nil, etc.

So I decided to write some category methods for NSString to help. However it's not working as expected and am wondering if someone can help me figure out why and possible help with a solution.

So here is what I came up with:

NSString+Extenstions.h

#import 

@interface NSString (Extensions)

- (NSString *)stringOrNil;
- (NSString *)stringOrEmpty;

@end

NSString+Extenstions.m

#import "NSString+Extensions.h"

@implementation NSString (Extensions)

- (NSString *)stringOrNil {
    return self == nil || [self length] == 0 ? nil : self;
}

- (NSString *)stringOrEmpty {
    return [self stringOrNil] == nil ? @"" : self;
}

@end

So the idea behind stringOrEmpty is to force the result as an empty NSString (not nil) if the object is nil or the length is 0.

Testing:

NSString *name = nil;
NSLog(@"%@", [name stringOrEmpty]); // result: (null)

I expected, the result above to be a blank, but the console logged it as (null). S I changed the stringOrEmpty method to return [[self stringOrNil] length] == 0 ? @"yes" : @"no"; and expected to see yes, but again got (null). It seems like stringOrEmpty is not being called.

Lastly I tested the following: NSLog(@"%@", [name class]); and again the result was (null).

Am I misunderstanding something? How can I write a category that will return a blank NSString value if the value is nil or truly empty?

Thanks!

Upvotes: 1

Views: 1627

Answers (1)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52203

nil isn't an instance of NSString or any object, so you can't deal with nil using instance methods.

A message to nil does nothing, it doesn't even get called. It just simply returns nil. You need to define them as class methods:

@interface NSString (Extensions)

+ (NSString *)stringOrNil:(NSString *)string;
+ (NSString *)stringOrEmpty:(NSString *)string;

@end

--

@implementation NSString (Extensions)

+ (NSString *)stringOrNil:(NSString *)string {
  return string.length ? string : nil;
}

+ (NSString *)stringOrEmpty:(NSString *)string {
  return string ? string : @"";
}

@end

Here is how you can call them:

NSString *name = nil;
NSLog(@"%@", [NSString stringOrEmpty:name]); // result: ("")

Upvotes: 3

Related Questions