objective c - My own @{} literals -
as know apple has provided @ literals such classes nsnumber, nsdictionary, nsarray, can create object way, example
nsarray *array = @[obj1, obj2];
so wonder, if there way create such literals own classes? example, want write smth.
myclass *object = myclass[value1, value2];
and don't want write long parsers :)
@
syntax literals, feature of clang
compiler. since compiler feature, no, cannot define own literals.
for more informations compilers literals, please refer clang 3.4 documentation - objective-c literals
edit: also, found this interesting discussion
edit: booranger mentioned @ comments, there exists method create []
accessors (the collection literals
way) access custom objects. called object subscripting
. using this, can access in custom class myobject[@"somekey"]
. read more @ nshipster.
here example implementation of "subcriptable" object. example simplicity, 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 access in object 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"]);
Comments
Post a Comment