Constants in Objective-C

后端 未结 14 1326
广开言路
广开言路 2020-11-21 22:10

I\'m developing a Cocoa application, and I\'m using constant NSStrings as ways to store key names for my preferences.

I understand this is a good idea b

14条回答
  •  旧时难觅i
    2020-11-21 23:03

    I use a singleton class, so that I can mock the class and change the constants if necessary for testing. The constants class looks like this:

    #import 
    
    @interface iCode_Framework : NSObject
    
    @property (readonly, nonatomic) unsigned int iBufCapacity;
    @property (readonly, nonatomic) unsigned int iPort;
    @property (readonly, nonatomic) NSString * urlStr;
    
    @end
    
    #import "iCode_Framework.h"
    
    static iCode_Framework * instance;
    
    @implementation iCode_Framework
    
    @dynamic iBufCapacity;
    @dynamic iPort;
    @dynamic urlStr;
    
    - (unsigned int)iBufCapacity
    {
        return 1024u;
    };
    
    - (unsigned int)iPort
    {
        return 1978u;
    };
    
    - (NSString *)urlStr
    {
        return @"localhost";
    };
    
    + (void)initialize
    {
        if (!instance) {
            instance = [[super allocWithZone:NULL] init];
        }
    }
    
    + (id)allocWithZone:(NSZone * const)notUsed
    {
        return instance;
    }
    
    @end
    

    And it is used like this (note the use of a shorthand for the constants c - it saves typing [[Constants alloc] init] every time):

    #import "iCode_FrameworkTests.h"
    #import "iCode_Framework.h"
    
    static iCode_Framework * c; // Shorthand
    
    @implementation iCode_FrameworkTests
    
    + (void)initialize
    {
        c  = [[iCode_Framework alloc] init]; // Used like normal class; easy to mock!
    }
    
    - (void)testSingleton
    {
        STAssertNotNil(c, nil);
        STAssertEqualObjects(c, [iCode_Framework alloc], nil);
        STAssertEquals(c.iBufCapacity, 1024u, nil);
    }
    
    @end
    

提交回复
热议问题