@
syntax are literals, which is feature of Clang
compiler. Since its compiler feature, NO, you cannot define you own literals.
For more informations about compilers literals, please refer Clang 3.4 documentation - Objective-C Literals
Edit: Also, I just found this interesting SO discussion
Edit: As BooRanger mentioned at the comments, there exists method to create []
accessors (the Collection Literals
way) to access custom objects. Its called Object Subscripting
. Using this, you can access anything in your custom class like this myObject[@"someKey"]
. Read more at NSHipster.
Here is my example implementation of "Subcriptable" object. For example simplicity, it just accesses internal dictionary. Header:
@interface LKSubscriptableObject : NSObject
// Object subscripting
- (id)objectForKeyedSubscript:(id <NSCopying>)key;
- (void)setObject:(id)obj forKeyedSubscript:(id <NSCopying>)key;
@end
Implementation:
@implementation LKSubscriptableObject {
NSMutableDictionary *_dictionary;
}
- (id)init
{
self = [super init];
if (self) {
_dictionary = [NSMutableDictionary dictionary];
}
return self;
}
- (id)objectForKeyedSubscript:(id <NSCopying>)key
{
return _dictionary[key];
}
- (void)setObject:(id)obj forKeyedSubscript:(id <NSCopying>)key
{
_dictionary[key] = obj;
}
@end
You can then access to anything in this object simply using square brackets:
LKSubscriptableObject *subsObj = [[LKSubscriptableObject alloc] init];
subsObj[@"string"] = @"Value 1";
subsObj[@"number"] = @2;
subsObj[@"array"] = @[@"Arr1", @"Arr2", @"Arr3"];
NSLog(@"String: %@", subsObj[@"string"]);
NSLog(@"Number: %@", subsObj[@"number"]);
NSLog(@"Array: %@", subsObj[@"array"]);