Reputation: 2177
I'm quite new to Obj-c and i'm trying to figure out how to use global functions. I'm working on a small project where i talk to a PHP API and this sets a session cookie, i have found how the get the cookie data, now i want to make it a little more effective by making a NSString function that gets the latest cookie value... And i am confused...
I have created a Globals object class, "Globals.h" and "Globals.m".
How do i declare a function and then access it from another file?
What i have now, Globals.h
#import <Foundation/Foundation.h>
@interface Globals : NSObject
-(NSString*)GlobalString;
@end
and Globals.m:
#import "Globals.h"
@implementation Globals
-(NSString *)Globalstring
{
return @"This is a global string!";
}
@end
I understand that i have to #import the Globals.h in the files where i want to use this, but i can't see this NSString function. Help? Good link for tips and tutorials for beginners like me?
Upvotes: 0
Views: 72
Reputation: 45598
Using -
before the method name makes it an instance method. You probably want a class/static method so that it can be invoked on NSString
directly. Use a +
instead:
+(NSString*)GlobalString;
And to use it:
NSString *foobar = [NSString GlobalString];
Also note that Objective-C methods are usually camelCase
not CapsCase
.
Upvotes: 2
Reputation: 14068
You could create a globals object that contains all global variables. If you do that have a look at the singleton pattern. By doing so you could fetch your globalString by someString = [Globals globalString];
if you design it as a class method rather than an instance method.
Hovever you could use your application delegate as a container for values and functions of globlal charachter. You can allways access your delegate by
MyAppDelegate *myDelegate = (MyAppDelegate) [[UIApplication sharedApplication] delegate];
and then access your global function - which is now a method of MyAppDelegate:
returnValue = [myDelegate myGlobalFunction:theParameter];
Upvotes: 0
Reputation: 16422
You need to declare an instance of Globals and then call GlobalString:
You could make GlobalString a class method + (NSString *)GlobalString
or declare a C function in a .c file.
Upvotes: 0