首页 > 编程语言 > 详细

自定义类实现基于数组/字典Literal Syntax设置和获取数据

时间:2015-06-03 12:03:58      阅读:183      评论:0      收藏:0      [点我收藏+]

.h文件

#import <Foundation/Foundation.h>

@interface TestKVC : NSObject {
    
    NSMutableDictionary *mDictionary;
    NSMutableArray *mArray;
}

- (void)setObject:(id)object forKeyedSubscript:(id < NSCopying >)aKey;
- (id)objectForKeyedSubscript:(id)key;

- (void)setObject:(id)anObject atIndexedSubscript:(NSUInteger)index;
- (id)objectAtIndexedSubscript:(NSUInteger)idx;

@end

.m文件

#import "TestKVC.h"

@implementation TestKVC

- (id)init {
    
    self = [super init];
    if (self) {
        mArray = [NSMutableArray array];
        mDictionary = [NSMutableDictionary dictionary];
    }
    
    return self;
}

- (void)setObject:(id)anObject atIndexedSubscript:(NSUInteger)index {
    [mArray insertObject:anObject atIndex:index];
}

- (id)objectAtIndexedSubscript:(NSUInteger)idx {
    return [mArray objectAtIndex:idx];
}

- (void)setObject:(id)object forKeyedSubscript:(id < NSCopying >)aKey {
    [mDictionary setObject:object forKey:aKey];
}

- (id)objectForKeyedSubscript:(id)key {
    return [mDictionary objectForKey:key];
}

@end


使用

    TestKVC *test = [[TestKVC alloc] init];
    test[@"key"] = @"Hello";
    id value = test[@"key"];
    
    [test setObject:@"World" forKeyedSubscript:@"key0"];
    id value0 = [test objectForKeyedSubscript:@"key0"];
    
    NSLog(@"%@ %@", value, value0);  // Hello World
    
    
    test[0] = @"Hello";
    test[1] = @"World";
    
    id v0 = test[0];
    id v1 = test[1];
    
    NSLog(@"%@  %@", v0, v1);         // Hello World


自定义类实现基于数组/字典Literal Syntax设置和获取数据

原文:http://my.oschina.net/u/734027/blog/424186

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!