Tuesday, October 16, 2012

objective-c methods; - vs +

So you've been funning around with Objective C and while in Objective C land you've no doubt noticed these little ticks in front of your methods - and others with +

what does it all mean?

While trying to implement a way to find if a string is empty (truly empty, nil (aka null) or filled with whitespaces) I bumped into a neat solution @ http://stackoverflow.com/questions/3436173/nsstring-is-empty
 
+ (BOOL)isEmptyString:(NSString *)string {
// Returns YES if the string is nil or equal to @""
{
// Note that [string length] == 0 can be false 

// when [string // isEqualToString:@""] is true, because these are Unicode strings.

if (((NSNull *) string == [NSNull null]) || (string == nil) ) {
return YES;
}
string = [string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];

if ([string isEqualToString:@""]) {

return YES;
}

return NO;
}
 

But what sparked up a thought here was that they were using + ClassMethod , and many times while I'm digging around for a solution many are simply -intanceMethods

so what does that mean? One way to think about it, is if I made the above function

an -instance method, then I would call it in my solution like this:

bool boolResult = [self isEmptyString:myStringVariable];


in a +class method
I create a new class (.h and .m files)
in my header:

#import <Foundation/Foundation.h>
@interface NSString (AdditionalStringFunctions)
+ (BOOL)isEmptyString:(NSString *)string;

@end

in my implementation I added the function:
#import "NSString+AdditionalStringFunctions.h"

@implementation NSString (AdditionalStringFunctions)

+ (BOOL) stringIsEmpty:(NSString *) aString {
  
    if ((NSNull *) aString == [NSNull null]) {
        return YES;
    }
  
    if (aString == nil) {
        return YES;
    } else if ([aString length] == 0) {
        return YES;
    } else {
        aString = [aString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
        if ([aString length] == 0) {
            return YES;
        }
    }
  
    return NO;
}

@end


Now I get to use it like this:

NSString *myString = [[NSString alloc] init];
myString = @"SomeString";

if([NSString stringIsEmpty:myString]) {
   NSLog(@"Your String is empty!");
}
else{
   NSLog(@"Your String is NOT empty!");
 }  


I'll take some time later to look into how to make it be more usable something like:

[myString isStringEmpty]; sort of like the length function

No comments:

Post a Comment