Global static const string variables in objective-c - objective-c

(Newbie alert)
I'm having trouble initializing a constant static string in objective-C:
Basically what I want to do is create a constant string from a NSLocalizedStringWithDefaultValue(...)
Any ideas?

Declare a static string in one of your implementation files. In either the class's initialize method or another appropriate setup point (depending on the exact circumstances — the sharedInstance method would be a good place in a singleton, for example), assign the localized string to the variable.

Related

Global vs Static variables in Objective-C [duplicate]

These lines are both in the implementation file above the #implementation declaration.
NSString * const aVar = #"aVarStringValue";
static NSString *aVar = #"aVarStringValue";
As far as I understand, the second static is allocated once only within the lifetime of the application and this fact contributes to performance.
But does this mean it is essentially a memory leak seeing as that block of memory will never be released?
And does the first const declaration get allocated every time it is accessed in contrast?
static keyword in Objective-C (and C/C++) indicates the visibility of the variable. A static variable (not in a method) may only be accessed within that particular .m file. A static local variable on the other hand, gets allocated only once.
const on the other hand, indicates that the reference may not be modified and/or reassigned; and is orthogonal on how it can be created (compilers may optimize consts though).
It's worth mentioning that NSString literals get initialized and never get destroyed in the life of application. They are allocated in a read-only part of the memory.
The static only changes the scope of the variable, not how it is declared or stored.
In both cases, the compiler will create a constant version of the NSString instance that is stored in the mach-o file. Thus, there is only ever one instance of either (note that you can change the behavior to cause the string to be dynamically created on load of the mach-o, but there is still just one instance).
The static just marks the aVar variable as being visible within the scope of the compilation unit -- the file -- only. Without the static, you could redeclare the string as extern NSString *aVar; in a header somewhere and have access to it from anywhere.
The const is orthogonal and, in the case of of NSString reference is pretty much entirely irrelevant.
In order to resolve all possible discussions on need of static and position of const:
According to C99/GNU99 specification (which usually used for Objective-C code):
static
is storage-class specifier
objects of file level scope by default has external linkage
objects of file level scope with static specifier has internal linkage
const
is type-qualifier (is a part of type)
keyword applied to immediate left instance - i.e.
MyObj const * myVar; - unqualified pointer to const qualified object type
MyObj * const myVar; - const qualified pointer to unqualified object type
Leftmost usage - applied to the object type, not variable
const MyObj * myVar; - unqualified pointer to const qualified object type
THUS:
static NSString * const myVar; - constant pointer to immutable string with internal linkage.
Absence of the static keyword will make variable name global and might lead to name conflicts within the application.

Static block variable in Objective-C

Is it possible to have a static variable of a "block type"?
I have a class that only does stuff in static methods. Upon execution of those methods i'm calling statusChangedBlock. Just for that i create a shared instance of the class, and use its single block property. I wonder if it's possible to have a static block variable; so i wouldn't have to create a instance with a single property, just for notifying that my status changed.
I know there is an option of NSNotification, but i don't like using it, with some rare exceptions.
...this question somehow sounds stupid, i can't tell why. I hope someone points that out.
to declare a static variable of block type
typedef ReturnType (^MyBlockType)(ArgumentType, ArgumentType2);
static MyBlockType myblock;
static MyBlockType myblock2;
or
static ReturnType (^myblock)(ArgumentType, ArgumentType2);
A block type variable is actually a pointer, similar to an object. You can have a static block variable, but you must assign its value at runtime, perhaps using a dispatch_once block.

Automatically running a selector on instance creation

In Objective-C, is there any way to run a specific selector automatically every time an object is instantiated? (I know about +initialize but I need an instance method).
Specifically, I am writing a custom string class (that inherits from my own root class with a similar interface to NSObject) and I am trying to make it 'play nicely' with Objective-C constant strings. To do this, I have the following class definition (as required by the runtime):
// 1) Required Layout
#interface MYConstantString : MYObject {
//Class isa; inherited from MYObject
char *c_string;
unsigned int length;
}
Now, I want to implement my string class by using a pointer to a C-struct inside the class (this "C object" is already well implemented so I basically just want to wrap it in an Objective-C class). Ideally therefore, my Objective-C class would look like this:
// 2) Desired Laout
#interface MYConstantString : MYObject {
// Class isa;
StringObject *string;
}
And then the class and instance methods would just wrap C function calls using that StringObject.
So because I can't have the desired ivar layout (2), I wish to hack around the required ivar layout (1) to work for me. For example:
- (void)fixup {
// Pseudocode
temp = copystring(c_string);
c_string = (void *)StringObjectNewWithString(temp); // Fudge pointer
length = ... // I can do something else with this.
}
So, to return to the question, is there a way to call -fixup automatically, rather than having to do the following every time I make write an Objective-C constant string?
MYConstantString *str = #"Constant string";
[str fixup];
I know this is an obscene hack, and Objective-C constant string interoperability isn't totally crucial for what I need, but it would be nice to be able to use the #"" syntax and make the code more 'naturally' Objective-C.
I'm guessing you left out an important fact: you're using -fconstant-string-class=MYConstantString when building to have the compiler use your class for constant string objects (#"...").
Given that, then, no. There are two significant problems. First, "instance creation" for constant strings happens at compile time, not run time. The reason that there's a required layout is that the compiler does nothing but lay out the string's data in a data section with a reference to the appropriate class object where the isa pointer goes. It doesn't invoke any custom code. It is not necessarily even aware of such custom code at compile time. A given translation unit may not include the constant string class. The reference to that is resolved at link time.
Second, the constant string instance is almost certainly laid out in a read-only data section. There's a good chance that even calling your -fixup method manually as in your question would encounter an access violation because you'd be modifying read-only memory.
You should consider using a class cluster. Make MYConstantString one concrete subclass of an abstract base class. Make it conform to the required layout and just use the character pointer and length ivars as they are. If it would be convenient to translate to StringObject at various points, do that at those points. Implement other, separate concrete subclasses to use StringObject internally, if desired.
MYConstantString *str = #"Constant string";
That can't work because #"..." is an NSString, and it's not only a problem of layout but of instance sizes. If you want 0-copy or anything like that, what you have to do is have something like:
MYConstantString *str = [MyConstantString stringWithNSString:#"Constant string"];
and let -stringWithNSString: recognize when the passed string is a constant one (I'm pretty sure the concrete class of constant strings is easy to recognize, and probably hasn't changed ever for backward compatibility reasons) and then hack it around to grab the pointer to the bytes and similar things.

static NSStrings in Objective-C

I frequently see a code snippet like this in class instance methods:
static NSString *myString = #"This is a string.";
I can't seem to figure out why this works. Is this simply the objc equivalent of a #define that's limited to the method's scope? I (think) I understand the static nature of the variable, but more specifically about NSStrings, why isn't it being alloc'd, init'd?
Thanks~
I think the question has two unrelated parts.
One is why isn't it being alloc'ed and init'ed. The answer is that when you write a Objective-C string literal of the #"foo" form, the Objective-C compiler will create an NSString instance for you.
The other question is what the static modifier does. It does the same that it does in a C function, ensuring that the myString variable is the same each time the method is used (even between different object instances).
A #define macro is something quite different: It's "programmatic cut and paste" of source code, executed before the code arrives at the compiler.
Just stumbled upon the very same static NSString declaration. I wondered how exactly this static magic works, so I read up a bit. I'm only gonna address the static part of your question.
According to K&R every variable in C has two basic attributes: type (e.g. float) and storage class (auto, register, static, extern, typedef).
The static storage class has two different effects depending on whether it's used:
inside of a block of code (e.g. inside of a function),
outside of all blocks (at the same level as a function).
A variable inside a block that doesn't have it's storage class declared is by default considered to be auto (i.e. it's local). It will get deleted as soon as the block exits. When you declare an automatic variable to be static it will keep it's value upon exit. That value will still be there when the block of code gets invoked again.
Global variables (declared at the same level as a function) are always static. Explicitly declaring a global variable (or a function) to be static limits its scope to just the single source code file. It won't be accessible from and it won't conflict with other source files. This is called internal linkage.
If you'd like to find out more then read up on internal and external linkage in C.
You don't see a call to alloc/init because the #"..." construct creates a constant string in memory (via the compiler).
In this context, static means that the variable cannot be accessed out of the file in which it is defined.
For the part of NSString alloc, init:
I think first, it can be thought as a convenience, but it is not equally the same for [[NSString alloc] init].
I found a useful link here. You can take a look at that
NSString and shortcuts
For the part of static and #define:
static instance in the class means you can access using any instance of the class. You can change the value of static. For the function, it means variable's value is preserved between function calls
#define is you put a macro constant to avoid magic number and string and define function macros. #define MAX_NUMBER 100. then you can use int a[MAX_MUMBER]. When the code is compiled, it will be copied and pasted to int a[100]
It's a special case init case for NSString which simply points the NSString pointer to an instance allocated and inited at startup (or maybe lazily, I'm not sure.) There is one one of these NSString instances created in this fashion for each unique #"" you use in your program.
Also I think this is true even if you don't use the static keyword. Furthermore I think all other NSStrings initialized with this string will point to the same instance (not a problem because they are immutable.)
It's not the same as a #define, because you actually have an NSString variable by creating the string with the = #"whatever" initialization. It seems more equivalent to c's const char* somestr = "blah blah blah".

const vs static NSStrings in Objective-C

These lines are both in the implementation file above the #implementation declaration.
NSString * const aVar = #"aVarStringValue";
static NSString *aVar = #"aVarStringValue";
As far as I understand, the second static is allocated once only within the lifetime of the application and this fact contributes to performance.
But does this mean it is essentially a memory leak seeing as that block of memory will never be released?
And does the first const declaration get allocated every time it is accessed in contrast?
static keyword in Objective-C (and C/C++) indicates the visibility of the variable. A static variable (not in a method) may only be accessed within that particular .m file. A static local variable on the other hand, gets allocated only once.
const on the other hand, indicates that the reference may not be modified and/or reassigned; and is orthogonal on how it can be created (compilers may optimize consts though).
It's worth mentioning that NSString literals get initialized and never get destroyed in the life of application. They are allocated in a read-only part of the memory.
The static only changes the scope of the variable, not how it is declared or stored.
In both cases, the compiler will create a constant version of the NSString instance that is stored in the mach-o file. Thus, there is only ever one instance of either (note that you can change the behavior to cause the string to be dynamically created on load of the mach-o, but there is still just one instance).
The static just marks the aVar variable as being visible within the scope of the compilation unit -- the file -- only. Without the static, you could redeclare the string as extern NSString *aVar; in a header somewhere and have access to it from anywhere.
The const is orthogonal and, in the case of of NSString reference is pretty much entirely irrelevant.
In order to resolve all possible discussions on need of static and position of const:
According to C99/GNU99 specification (which usually used for Objective-C code):
static
is storage-class specifier
objects of file level scope by default has external linkage
objects of file level scope with static specifier has internal linkage
const
is type-qualifier (is a part of type)
keyword applied to immediate left instance - i.e.
MyObj const * myVar; - unqualified pointer to const qualified object type
MyObj * const myVar; - const qualified pointer to unqualified object type
Leftmost usage - applied to the object type, not variable
const MyObj * myVar; - unqualified pointer to const qualified object type
THUS:
static NSString * const myVar; - constant pointer to immutable string with internal linkage.
Absence of the static keyword will make variable name global and might lead to name conflicts within the application.