美文网首页
Objective-C 使用下标访问自定义类型的属性

Objective-C 使用下标访问自定义类型的属性

作者: Don_He | 来源:发表于2019-04-03 18:09 被阅读0次

    Objective-C 使用下标访问自定义类型的属性

    OC容器类

    在Objective-C中,可以通过下标来访问数组中的元素,如果数组是NSMutableArray类型的可变数组,则还可以通过下标来对数组中的元素进行赋值操作。例如:

    NSMutableArray<NSString *> *array = [[NSMutableArray<NSString *> alloc] init];
    
    array[0] = @"Hello world";
    
    NSString *string = array[0];
    

    对于Objective-C中的字典对象,可以通过键值下标的方式来进行访问,例如:

    NSMutableDictionary<NSString *, NSString *> *dictionary = [[NSMutableDictionary<NSString *, NSString *> alloc] init];
    
    dictionary[@"key"] = @"value";
    

    自定义下标访问类

    如果要像NSMutableArray和NSMutableDictionary那样访问属性,主要需要实现4个方法,如下:

    - (id)objectAtIndexedSubscript:(NSUInteger)index; // object = array[index];
    
    
    - (void)setObject:(id)object atIndexedSubscript:(NSUInteger)index; // array[index] = object;
    
    - (id)objectForKeyedSubscript:(NSString *)key; // id value = dictionary[@"key"];
    
    - (void)setObject:(id)object forKeyedSubscript:(NSString *)key; // dictionary[@"key"] = value;
    

    举个例子:

    // MyObject.h
    @interface MyObject : NSObject
    
    - (id)objectAtIndexedSubscript:(NSUInteger)index;
    
    - (void)setObject:(id)object atIndexedSubscript:(NSUInteger)index;
    
    - (id)objectForKeyedSubscript:(NSString *)key;
    
    - (void)setObject:(id)object forKeyedSubscript:(NSString *)key;
    
    @end
    
    #import "MyObject.h"
    
    @interface MyObject ()
    
    @property(nonatomic, strong) NSString *object0;
    
    @property(nonatomic, strong) NSString *object1;
    
    @property(nonatomic, strong) NSString *object;
    
    @end
    
    @implementation MyObject
    
    - (id)objectAtIndexedSubscript:(NSUInteger)index {
        return [self valueForKey:[NSString stringWithFormat:@"object%lu", (unsigned long)index]];
    }
    
    - (void)setObject:(id)object atIndexedSubscript:(NSUInteger)index {
        [self setValue:object forKey:[NSString stringWithFormat:@"object%lu", (unsigned long)index]];
    }
    
    - (id)objectForKeyedSubscript:(NSString *)key {
        return [self valueForKey:key];
    }
    
    - (void)setObject:(id)object forKeyedSubscript:(NSString *)key {
        [self setValue:object forKey:key];
    }
    
    @end
    

    必须在头文件中声明这4个方法,才能为当前类型添加下标访问的语法糖。


    error.png

    以上为头文件没有声明方法的报错。

    总结

    这个特性一般来说用不上,并且相对Swift的Subscripts来说显得功能性比较弱,大家可以结合项目需要使用。如果有比较不错的使用场景,欢迎赐教。

    相关文章

      网友评论

          本文标题:Objective-C 使用下标访问自定义类型的属性

          本文链接:https://www.haomeiwen.com/subject/vpzzbqtx.html