Search code examples
objective-cmethodscalldeclare

How do I call this method in objective-C (iOS)?


I have spent literally hours and hours trying to find the answer to this. I have tried [what I feel anyway!] to be everything. And I cannot call this method in my code with out getting this error:

Receiver type NSString for instance message does not declare a method with selector returnAsDoubleDigits:

I was trying to refactor my code so I could reuse this method to return single digit numbers (converted to NSString) as double digit strings (i.e. 4 becomes 04).

Please can anyone help me here? Have I even declared it correctly etc.? Thank you so much! :)

Call something like:

[doubleDigitString returnAsDoubleDigits: singleDigitString];

Header file:

- (NSString *)returnAsDoubleDigits: (NSString *)digits;

Implementation file:

- (NSString *)returnAsDoubleDigits: (NSString *)digits {
    if (digits.length == 1) return [NSString stringWithFormat: @"0%@", digits];
    else return [NSString stringWithFormat: @"0%@", digits];
}

Solution

  • Where are you calling it from? in the same class? Is this what you intended?

    NSString* doubleDigitString = [self returnAsDoubleDigits:digits];
    

    You could always use categories too.

    @implementation NSString (mycategory)
    
    
    -(NSString *) returnAsDoubleDigits
    {
       NSString* doubleDigits = nil;
       if (self.length == 1) {
        doubleDigits = [NSString stringWithFormat: @"0%@",
                        self];
       } else {
        doubleDigits = [NSString stringWithFormat: @"0%@",
                          self];
       }
       return doubleDigits;
    }
    @end
    

    and then use

     NSString* doubleDigitString = [singleDigitString returnAsDoubleDigits];