On Aug 9, 2011, at 3:47 AM, Devraj Mukherjee wrote:

> I am writing an API client for a REST service, parts of the REST API
> returns fixed String values. E.g. status of an order.
> 
> I want to represents these fixed responses as constants. I have
> represented fixed numeric values using enums and used a typedef to
> represent the data type.
> 
> Are Strings defined using #define good enough as String constants?
> 
> Or Should I be doing this another way?

When working with a framework like Cocoa, I'd follow its lead.

In this case, that's to define global constant NSString pointers:

  // --- in MWSService.h
  
  /*! Default endpoint URL for MWSService. */
  MWS_EXPORT NSString * const MWSServiceDefaultEndpointURL;

  // --- in MWSService.m
  
  NSString * const MWSServiceDefaultEndpointURL = 
@"http://www.example.com/endpoint";;

The macro MWS_EXPORT should be the typical "extern without C++ name mangling" 
macro:

  #if defined(__cplusplus)
  #define MWS_EXPORT extern "C"
  #else
  #define MWS_EXPORT extern

This is needed because if you compile some of your code as Objective-C and 
other as Objective-C++, without the "C" part of 'extern "C"' your global can 
wind up with C++ name mangling.

The "NSString * const" means the pointer is constant, so the optimizer can 
assume it's unchanging.  That'll be the case because you'll wind up with only 
one copy of the string in your built product (whether it's a library or 
executable).

That won't necessarily be the case for a #define - if you used a #define in a 
framework header, and built an OS X app that embeds the framework, you'd 
actually have separate copies of the string in the app and the framework.  (And 
-isEqual: implementations are generally smart about immediately returning YES 
when passed self, but falling back when not.)

In short: Do like Apple, use an "NSString * const" global.

  -- Chris

_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to