In Ruby, we have symbols to use for the key of hashes. I'm trying to port a Ruby library to Objective-C, and the library has a hash in it that uses symbols as keys. Is there any similar soulution for Objective-C? Or should I be using NSStrings?
            Asked
            
        
        
            Active
            
        
            Viewed 288 times
        
    0
            
            
         
    
    
        Linuxios
        
- 34,849
- 13
- 91
- 116
- 
                    Objective-C is a super-set of C, so you might be able to use `#define` constants to achieve a similar outcome. – Sahand Apr 02 '12 at 17:25
- 
                    call a to_s on all the symbols, and you have strings available to use as your keys (symbols are mutable strings) – bjhaid Apr 02 '12 at 17:36
- 
                    I;m talking about symbols in Objective-C, not Ruby. – Linuxios Apr 02 '12 at 17:48
2 Answers
2
            
            
        I've seen declarations like
extern NSString *const NSKeyValueChangeNewKey = @"NSKeyValueChangeNewKey";
so that you can use it as a key:
[dict objectForKey:NSKeyValueChangeNewKey];
For an explanation that's a bit more detailed, see Constants in Objective-C.
 
    
    
        Community
        
- 1
- 1
 
    
    
        Sophie Alpert
        
- 139,698
- 36
- 220
- 238
- 
                    
- 
                    
- 
                    For the record: Please don't prefix your constants with "NS" — that's Apple's prefix. – Chuck Apr 02 '12 at 18:49
- 
                    @Chuck: Sorry, I was trying to pseudo-quote from Apple source code. I'll change to hmt's example to be a bit more clear. – Sophie Alpert Apr 02 '12 at 20:26
0
            NSDictionary keys in Objective-C are usually NSStrings. That's probably the way to go here.
You don't have to worry about Ruby string literals vs. symbols; just create an NSString with the string value for the key or use a literal @"my key name" string as required.
 
    
    
        gregheo
        
- 4,182
- 2
- 23
- 22
- 
                    @benalpert 's answer is the better answer. The use of a symbol is idiomatic in Ruby because they are immutable and are only created once. In Objective-C a const pointer to a string is the equivalent that you want to use. – Paul.s Apr 02 '12 at 18:26