Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class with defined static constant values in Objective-C

I want to create a class that will contains static values accessable from all project.

Pseudocode:

class Constants:
  constant String API_URL : "http://api.service.com"
  constant Integer SOME_VALUE : 7

How can I do this with Objective-C ?

like image 345
hsz Avatar asked Apr 18 '13 11:04

hsz


People also ask

How do you declare a constant in Objective-C?

Defining ConstantsUsing #define preprocessor. Using const keyword.

What is a static variable in Objective-C?

In both C and Objective-C, a static variable is a variable that is allocated for the entire lifetime of a program. This is in contrast to automatic variables, whose lifetime exists during a single function call; and dynamically-allocated variables like objects, which can be released from memory when no longer used.

Can static class have constants C#?

Constant fields or local variables must be assigned a value at the time of declaration and after that, they cannot be modified. By default constant are static, hence you cannot define a constant type as static.

What is a constants class?

Constants are immutable values which are known at compile time and do not change for the life of the program. Constants are declared with the const modifier. Only the C# built-in types (excluding System. Object) may be declared as const . User-defined types, including classes, structs, and arrays, cannot be const .


1 Answers

Answer for your question is extern keyword . I will explain it to you using an example . Add objective c classes your project and name them Common , Now in Common.h

     @interface Common : NSObject

     extern NSString *SiteApiURL;

     @end

After you defined an instance of NSString Class using the extern keyword what you need to do is switch to Common.m class and initialize the value for NSString (SiteApiURL)

     #import "Common.h"

     @implementation Common

     NSString *SiteApiURL = @"http://api.service.com";

     @end

Import the Common.h class within the project-Prefix.pch file like this

    #import <Availability.h>

    #ifndef __IPHONE_3_0
    #warning "This project uses features only available in iOS SDK 3.0 and later."
    #endif

    #ifdef __OBJC__
        #import <UIKit/UIKit.h>
        #import <Foundation/Foundation.h>
        #import "Common.h"
    #endif

All done , now you can use the object "SiteApiURL" anywhere in the whole project and you need not to import any class anywhere i.e. You can use this variable anywhere in the project directly.

like image 81
Gaurav Rastogi Avatar answered Oct 06 '22 00:10

Gaurav Rastogi