views:

122

answers:

3

How can I use an NSString in a file where that string wasn't created?

ex. I created a string in thisone.m, but I want to use the same sting (ie the same data) in thatone.m the data from this string will be coming from a UITextField

+1  A: 

I'm not sure exactly what your asking but there are many ways to share data between files (or objects). You can define it as an instance variable in one class and take a reference to the object instance in other class. You can pass the data to a method called on the other object, or you can share it as a global variable by making it an instance variable of UIApplication.

Again, without being more specific in your question, this should get you thinking along the right path.

As a simple example:

@interface MyObject : NSObject {
     NSString *mystring;
}
ennuikiller
how can I make an NSString an instance variable?
Matt S.
ok, so how would I go about doing everything from there.... Do I have to do anything in the .m?
Matt S.
+1  A: 

If you don't have access to the thisone object, you can store the string as a ThisOne class variable, as long as you don't need a different one for each of your objects. Put the in your class (not inside a method, but outside of the @implementation)

extern BOOL theString;

The access is by

[ThisOne theString];

This is not as good as ennuikiller's answer, but it might be what you need.

coneybeare
ok, so I have it close, however I'm getting errors (may not respond to '+string'), so at least I know it's kinda working
Matt S.
put it in the .h file, outside of the @interface.
coneybeare
I'm still getting the error...
Matt S.
A: 

I know some people don't like #define's, but they work well for this old-school C programmer.

In each project, I have a file "Strings.h" which contains a bunch of #define's, such as:

#define SK_String_I_Want_To_Display   @"String I Want To Display"

(where SK_ is my preface to indicate "string constant".)

For localization, I have another file called "LocalStrings.h" with strings like:

#define SK_LOCAL(a) NSLocalizedString(@a, "") // keeps string defs simple
#define SK_Localized_String   SK_LOCAL("Localized String")
#define SK_Another_String     SK_LOCAL("Another String")

Then I just #import "Strings.h" or "LocalStrings.h" where needed. Because I have all localized strings in one file it's easy to make sure I have localized everything.

The biggest issue with this approach is that you have to be careful not to do something like this:

#define SK_Another_String     SK_LOCAL("Another String");

--- as that semicolon at the end can cause tricky bugs that are hard to find.

The overhead of having the #define expanded in place is pretty low. Compiles take a bit longer if you change one of these .h files, but I find the solution works well.

Amagrammer