john doe
john doe

Reputation: 9660

NSString Category Method Not Getting Called

The problem I am trying to solve is to convert nil strings into empty strings so I can put that as a value in NSDictionary.

I have the following code:

//Accessed in class  
prospect.title = [self.titleLabel.text emptyWhenNil];

// NSString+Additions Category

-(NSString *) emptyWhenNil
{
   if(self == nil)
      return @"";

   return self;
 }

But for some reason the emptyWhenNil method is never even invoked!! I am lost..

Upvotes: 1

Views: 1166

Answers (3)

MByD
MByD

Reputation: 137312

If the NSString pointer is nil, the method will not be called on it, what you can do is create a static method:

+ (NSString *) emptyIfNil:(NSString *) str
{
    return str == nil ? @"" : str;
}

Upvotes: 1

DrummerB
DrummerB

Reputation: 40211

The problem is, when your string pointer is nil, you have no object to send that category message to. Messages to nil are not executed (and return nil) in Objective-C.

If you want to put "null" objects into a collection, such as an NSDictionary, or NSArray, you can use the NSNull class instead.

Alternatively you could implement this method as a class method:

+ (NSString *)emptyStringIfNil:(NSString *)str {
    if (!str) return @"";
    return str;
}

You would then call this as

prospect.title = [NSString emptyStringIfNil:self.titleLabel.text];

Upvotes: 13

Mike Weller
Mike Weller

Reputation: 45598

If the string is nil, there is no self to execute the method on. The default behaviour of the runtime in this situation is to return a default nil value.

You should implement this as a static method instead. Something like this:

+ (NSString *)emptyStringIfNil:(NSString *)input
{
    return input ? input : @"";
}

Upvotes: 1

Related Questions