标签:
//
// main.m
// objCTest
//
// Created by Zenny Chen on 12-2-7.
// Copyright (c) 2014年 Neon Media Studio. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface MyContainer : NSObject
{
@private
NSMutableDictionary *mDict;
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
@implementation MyContainer
- (instancetype)init
{
self = [super init];
mDict = [[NSMutableDictionary alloc] initWithDictionary:@{@"key1":@"value1", @"key2":@"value2"}];
mArray = [[NSMutableArray alloc] initWithArray:@[@100, @200, @300, @400]];
return self;
}
- (void)dealloc
{
if(mDict != nil)
{
[mDict removeAllObjects];
[mDict release];
mDict = nil;
}
if(mArray != nil)
{
[mArray removeAllObjects];
[mArray release];
mArray = nil;
}
[super dealloc];
}
- (void)setObject:(id)object forKeyedSubscript:(id < NSCopying >)aKey
{
[mDict setObject:object forKey:aKey];
}
- (id)objectForKeyedSubscript:(id)key
{
return [mDict objectForKey:key];
}
- (void)setObject:(id)anObject atIndexedSubscript:(NSUInteger)index
{
const NSUInteger length = [mArray count];
if(index > length)
return;
if(index == length)
[mArray addObject:anObject];
else
[mArray replaceObjectAtIndex:index withObject:anObject];
}
- (id)objectAtIndexedSubscript:(NSUInteger)idx
{
if(idx >= [mArray count])
return nil;
return [mArray objectAtIndex:idx];
}
@end
int main (int argc, const char * argv[])
{
@autoreleasepool
{
// insert code here...
MyContainer *cont = [[MyContainer alloc] init];
cont[@"mykey"] = @"myvalye";
NSLog(@"key1 is: %@", cont[@"key1"]);
NSLog(@"key2 is: %@", cont[@"key2"]);
NSLog(@"mykey is: %@", cont[@"mykey"]);
cont[4] = @500;
cont[2] = @-300;
NSLog(@"The value[4] = %@", cont[4]);
NSLog(@"The value[3] = %@", cont[3]);
NSLog(@"The value[2] = %@", cont[2]);
}
return 0;
}
|
Objective-C如何自己实现一个基于数组下标的属性访问模式
标签:
原文地址:http://www.cnblogs.com/leidaxie/p/4596192.html