gpt4 book ai didi

objective-c - 我自己的@{} 文字

转载 作者:行者123 更新时间:2023-12-04 04:49:02 24 4
gpt4 key购买 nike

如您所知,Apple 为 NSNumber、NSDictionary、NSArray 等类提供了 @literals,因此我们可以通过这种方式创建对象,例如

NSArray *array = @[obj1, obj2];

所以我想知道,是否有办法为我自己的类创建这样的文字?例如,我想写 smth。像
MyClass *object = MyClass[value1, value2];

而且我不想写长解析器:)

最佳答案

@语法是文字,这是 Clang 的特性编译器。由于其编译器特性, ,你不能定义你自己的文字。

有关编译器字面量的更多信息,请参阅 Clang 3.4 documentation - Objective-C Literals

编辑:另外,我刚刚发现 this有趣的 SO 讨论

编辑:正如 BooRanger 在评论中提到的,存在创建 [] 的方法访问器(Collection Literals 方式)来访问自定义对象。它叫 Object Subscripting .使用它,您可以像这样访问自定义类中的任何内容 myObject[@"someKey"] .阅读更多 NSHipster .

这是我的“Subcriptable”对象的示例实现。例如简单,它只访问内部字典。标题:

@interface LKSubscriptableObject : NSObject

// Object subscripting
- (id)objectForKeyedSubscript:(id <NSCopying>)key;
- (void)setObject:(id)obj forKeyedSubscript:(id <NSCopying>)key;

@end

实现:
@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

然后,您只需使用方括号即可访问此对象中的任何内容:
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"]);

关于objective-c - 我自己的@{} 文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17718790/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com