Saturday, February 21, 2009

Objective-C class method (function)

This is going to be a super quick and simple post about methods in the Objective-C language. I was trying to write a simple static method that would take 2 strings and then return the 2 strings together. I want this method to be static (no instance of a class required) and I thought it would be nice to put the method in its own class definition so I could expand upon it and add others to it.

So first create you a new xcode project or use an existing one and then add a Objective -C class file, its under Mac OS X then Cocoa. Be sure to leave the "Also create the .h" checked...

Put this in your .h file:

#import UIKit/UIKit.h>
@interface MyFunc : NSObject {
}
+ (NSString *)updateString:(NSString *)name age:(NSString *)ageIn;
@end

Put this in your .m file:

#import "MyFunc.h"
@implementation MyFunc
+ (NSString *)updateString:(NSString *)name age:(NSString *)ageIn{
return ([name stringByAppendingString:ageIn]);
}
@end


A few notes on what I had you copy, I named my file "MyFunc.m" and "MyFunc.h". The header just has your standard method definition but notice the + as opposed to the - that makes the method a class method and not a instance method. Let me explain the method definition (.m)

1) (NSString *) is your return type
2) updateString:(NSString *)name updateString = method name, (NSString *) parameter type, name is used inside the method and it is your first parameter value
3) age = second parameter, (NSString *) = second parameter type, ageIn is used inside the method for the second parameters value.

The first parameter and second parameter form the method signature "updateString:age"

OK so now you want to use the great method, well from another .m file in my project all I did was #import "MyFunc.h" and then used it like this inside another method:

1) NSString *tmp = [MyFunc updateString:(@"param 1 ")age:(@"param 2")];
2) NSLog(tmp);

Have ?'s, leave a comment...

No comments:

Post a Comment