Jeremy Smith
Jeremy Smith

Reputation: 15079

Are strings defined as constants not NSStrings?

I have a constant defined as:

#define BEGIN_IMPORT_STRING @"Importing Hands!";

But I get an error when I try to concat with:

NSString *updateStr = [NSString stringWithFormat:@"%@%@", BEGIN_IMPORT_STRING, @" - Reading "];

This doesn't happen if I replace it with a string literal

NSString *updateStr = [NSString stringWithFormat:@"%@%@", @"foo", @" - Reading "];

Or a local string

NSString *temp = @"foo";
NSString *updateStr = [NSString stringWithFormat:@"%@%@", temp, @" - Reading "];

Upvotes: 0

Views: 763

Answers (4)

Jon Reid
Jon Reid

Reputation: 20980

Aside from the accepted answer (remove semicolon), note that:

  • @"Foo" is an NSString. You can even send it a message.
  • #define FOO @"Foo" is a preprocessor macro, not a constant. It's a typing shortcut.

Though macros aren't an uncommon way to avoid retyping the same string, they're an unfortunate holdover. Essentially, they're playing games that aren't necessary anymore.

For repeated strings, I prefer:

static NSString *const Foo = @"Foo;

The const portion of this definition ensures that the pointer is locked down, so that Foo can't be made to point to a different object.

The static portion restricts the scope to the file. If you want to access it from other files, remove the static and add the following declaration to your header file:

extern NSString *const Foo;

Upvotes: 2

Tom Andersen
Tom Andersen

Reputation: 7200

Should you be using

   NSLocalizedString(@"Importing Hands!", @"Message shown when importing of hands starts");  

?

I put it as an answer because this looks like something you would not want to have to go and redo through all your code.

Upvotes: 1

Wevah
Wevah

Reputation: 28242

You need to remove the semicolon from your #define:

#define BEGIN_IMPORT_STRING @"Importing Hands!"

To the compiler, the resulting line looks like this:

NSString *updateStr = [NSString stringWithFormat:@"Importing Hands!";, @" - Reading "];

Upvotes: 4

Nekto
Nekto

Reputation: 17877

Replace

#define BEGIN_IMPORT_STRING @"Importing Hands!";

with

#define BEGIN_IMPORT_STRING @"Importing Hands!"

This is because compiler in your case replaces all occurrences of BEGIN_IMPORT_STRING with @"Importing Hands!";

Upvotes: 4

Related Questions