program story

iOS 애플리케이션에서 전역 상수를 어디에 저장합니까?

inputbox 2020. 8. 2. 18:35
반응형

iOS 애플리케이션에서 전역 상수를 어디에 저장합니까?


iOS 앱의 대부분의 모델은 웹 서버를 쿼리합니다. 서버의 기본 URL을 저장하는 구성 파일을 갖고 싶습니다. 다음과 같이 보일 것입니다 :

// production
// static NSString* const baseUrl = "http://website.com/"

// testing
static NSString* const baseUrl = "http://192.168.0.123/"

한 줄 또는 다른 줄을 주석 처리하여 모델이 가리키는 서버를 즉시 변경할 수 있습니다. 내 질문은 iOS에 전역 상수를 저장하는 가장 좋은 방법은 무엇입니까? 안드로이드 프로그래밍에는이 내장 문자열 리소스 파일이 있습니다. 모든 Activity ( UIViewController 와 동일)에서 다음을 사용하여 해당 문자열 상수를 검색 할 수 있습니다.

String string = this.getString(R.string.someConstant);

iOS SDK에 상수를 저장할 수있는 비슷한 장소가 있는지 궁금합니다. 그렇지 않다면 Objective-C에서 가장 좋은 방법은 무엇입니까?


당신은 또한 할 수 있습니다

#define kBaseURL @"http://192.168.0.123/"

는 "상수"헤더 파일에 말 constants.h. 그런 다음

#include "constants.h"

이 상수가 필요한 모든 파일의 맨 위에

이런 식으로 다음과 같이 컴파일러 플래그에 따라 서버 간을 전환 할 수 있습니다.

#ifdef DEBUG
    #define kBaseURL @"http://192.168.0.123/"
#else
    #define kBaseURL @"http://myproductionserver.com/"
#endif

글쎄, 당신은 관련된 인터페이스에 대한 로컬 선언을 원합니다. 앱 전체 상수 파일은 좋지 않습니다.

또한 단순히 다음을 extern NSString* const사용하는 대신 기호 를 선언하는 것이 좋습니다 #define.


SomeFile.h

extern NSString* const MONAppsBaseUrl;

SomeFile.m

#import "SomeFile.h"

#ifdef DEBUG
NSString* const MONAppsBaseUrl = @"http://192.168.0.123/";
#else
NSString* const MONAppsBaseUrl = @"http://website.com/";
#endif

C ++ 호환 Extern 선언을 생략하는 것 외에도 Apple의 Obj-C 프레임 워크에서 일반적으로 사용되는 내용입니다.

상수 필요가 하나의 파일이나 기능을 볼 수하는 경우에, static NSString* const baseUrl당신의 *.m좋은입니다.


전역 상수를 정의하는 방법 :


AppConstants.h

extern NSString* const kAppBaseURL;

AppConstants.m

#import "AppConstants.h"

#ifdef DEBUG
NSString* const kAppBaseURL = @"http://192.168.0.123/";
#else
NSString* const kAppBaseURL = @"http://website.com/";
#endif

그런 다음 {$ APP} -Prefix.pch 파일에서 :

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

If you experience any problems, first make sure that you have the Precompile Prefix Header option set to NO.


You can also concatenate string constants like this:

  #define kBaseURL @"http://myServer.com"
  #define kFullURL kBaseURL @"/api/request"

  1. I define global constant in YOURPROJECT-Prefix.pch file.
  2. #define BASEURl @"http://myWebService.appspot.com/xyz/xx"
  3. then anywhere in project to use BASEURL:

    NSString *LOGIN_URL= [BASEURl stringByAppendingString:@"/users/login"];
    

Updated: In Xcode 6 you will not find default .pch file created in your project. So please use PCH File in Xcode 6 to insert .pch file in your project.

Updates: For SWIFT

  1. Create new Swift file [empty without class] say [AppGlobalMemebers]
  2. & Right away declare / define member

    Example:

    var STATUS_BAR_GREEN : UIColor  = UIColor(red: 106/255.0, green: 161/255.0, blue: 7/255.0, alpha: 1)  //
    
    1. If you want to define the app global member in any class file say Appdelegate or Singleton class or any, declare given member above class definition

I do think that another way to do this is far simpler and you will just include it in files you need them included in, not ALL the files, like with the .pch prefix file:

#ifndef Constants_h
#define Constants_h

//Some constants
static int const ZERO = 0;
static int const ONE = 1;
static int const TWO = 2;

#endif /* Constants_h */

After that you include this header file in the header file that you want. You include it in header file for the specific class that you want it included in:

#include "Constants.h"

Global declarations are interesting but, for me, what changed deeply my way to code was to have global instances of classes. It took me a couple of day's to really understand how to work with it so I quickly summarized it here

I use global instances of classes (1 or 2 per project, if needed), to regroup core data access, or some trades logics.

For instance if you want to have a central object handling all restaurant tables you create you object at startup and that is it. This object can handle database accesses OR handle it in memory if you don't need to save it. It's centralized, you show only useful interfaces ... !

It's a great help, object oriented and a good way to get all you stuff at the same place

A few lines of code :

@interface RestaurantManager : NSObject
    +(id) sharedInstance;
    -(void)registerForTable:(NSNumber *)tableId;
@end 

and object implementation :

@implementation RestaurantManager

+ (id) sharedInstance {
    static dispatch_once_t onceQueue;

    dispatch_once(&onceQueue, ^{
        sharedInstance = [[self alloc] init];
        NSLog(@"*** Shared instance initialisation ***");
    });
    return sharedInstance;
}

-(void)registerForTable:(NSNumber *)tableId {
}
@end

for using it it's really simple :

[[RestaurantManager sharedInstance] registerForTable:[NsNumber numberWithInt:10]]


An approach I've used before is to create a file Settings.plist and load it into NSUserDefaults upon launch using registerDefaults:. You can then access its contents with the following:

// Assuming you've defined some constant kMySettingKey.
[[NSUserDefaults standardUserDefaults] objectForKey:kMySettingKey];

While I haven't done any Android development, it sounds as though this is analogous to the strings resource file you described. The only downside is that you can't use the preprocessor to swap between settings (e.g. in DEBUG mode). I suppose you could load in a different file, though.

NSUserDefaults documentation.


For a number you can use it like

#define MAX_HEIGHT 12.5

The accepted answer has 2 weaknesses. First, as others pointed is usage of #define which is harder to debug, use instead extern NSString* const kBaseUrl structure. Second, it defines a single file for constants. IMO, this is wrong because most of classes don't need access to those constants or to access all of them plus file can become bloated if all constants are declared there. A better solution would be to modularize constants at 3 different layers:

  1. System layer: SystemConstants.h or AppConstants.h which describes constants at global scope, which can be accessed by any class in the system. Declare here only those constants that must be accessed from different classes that are not related.

  2. Module/Sub-system layer: ModuleNameConstants.h, describes a set of constants which are typical for a set of related classes, inside of a module/sub-system.

  3. Class layer: Constants resides in the class and are used only by it.

Only 1,2 are related to the question.


I'd use a configuration object that initializes from a plist. Why bother other classes with irrelevant external stuff?

I created eppz!settigns soley for this reason. See article Advanced yet simple way to save to NSUserDefaults for incorporating default values from a plist.

enter image description here

참고URL : https://stackoverflow.com/questions/7116177/where-to-store-global-constants-in-an-ios-application

반응형