开发者

Large Hidden Constant in Objective C

开发者 https://www.devze.com 2023-02-21 00:44 出处:网络
I have a large constant (an NSString with 10^6 values). Because of its size I would like to declare it at the end of the source file (so I don\'t have to scroll through it every time I want to edit my

I have a large constant (an NSString with 10^6 values). Because of its size I would like to declare it at the end of the source file (so I don't have to scroll through it every time I want to edit my code). Also because of its size I would like it to be a constant so I can load it at compile time instead of runtime. Also, because I do not want it accessible to outside users I do not want to declare it as extern in the header file.

I have it declared as a constant using the code below in the implementation file, however it is giving me a "Use of undeclared identifier 'hugeConstantString'" if I move it past the @end of the implementation (for obvious reasons).

NSString *const hugeConstantString = @"a_whooooooole_lotta_ch开发者_高级运维aracters";

I've checked this out: Constants in Objective-C but it didn't tell me anything I didn't know already. Maybe my brain is fried, but: is there any way that I can define this huge constant AFTER my implementation and still have it accessible? Or if I declare it in another header file and import it, will it then be accessible to others?

Thanks!


I'm not sure such a large string is a good idea, but if you're going to use it, I suggest putting it in its own header file.

MyLongStringConstant.h

#define kLongString @"..."

MyClass.h

....
#import "MyLongStringConstant.h"
...
//Do something with kLongString
...

If you want to have it accessible in every file of your app, import the header inside your apps myApp_Prefix.pch file, which is imported into every file.


I am going to save the conversation of Why are you doing that and just post a simple solution for you. Thanks to Tommy in the comments here is a simpler version.

#import "LargeStringTest.h"


@implementation LargeStringTest

//Declare the string
static NSString *hugeConstantString;

- (id)init {
    self = [super init];
    if (self) {
        NSLog(@"Large String %@", hugeConstantString);
    }
    return self;
}

//Place all other code here

//Assign the string
static NSString *hugeConstantString = @"a_whooooooole_lotta_characters";

@end
0

精彩评论

暂无评论...
验证码 换一张
取 消