18
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

クラスに [], {} を実装する

Last updated at Posted at 2015-08-08

iOS6 から使えます。

[]

下記のメソッドを定義します。

CustomClass.h
// id obj = custom[1]
- (id)objectAtIndexedSubscript:(NSUInteger)idx;
// custom[0] = @10
- (void)setObject:(id)obj atIndexedSubscript:(NSUInteger)idx;
CustomClass.m
- (id)objectAtIndexedSubscript:(NSUInteger)idx
{
  return object;
}
- (void)setObject:(id)obj atIndexedSubscript:(NSUInteger)idx
{
  ...
}

使うとき

Test.m
CustomClass *custom = [CustomClass new];
id obj    = custom[1];
custom[0] = @10;

{}

下記のメソッドを定義します。

CustomClass.h
// id obj     = custom[@1];
- (id)objectForKeyedSubscript:(id)key;
// custom[@1] = @0;
- (void)setObject:(id)anObject forKeyedSubscript:(id <NSCopying>)aKey;
CustomClass.m
- (id)objectForKeyedSubscript:(id)key
{
    return @"10";
}

- (void)setObject:(id)anObject forKeyedSubscript:(id <NSCopying>)aKey
{
    ...
}

使うとき

Test.m
CustomClass *custom = [CustomClass new];
id obj     = custom[@1];
custom[@1] = @0;

[], {}

上記二つを実装することで両方使えます。

Test.m
CustomClass *custom = [CustomClass new];

id arrayObj = custom[1];
custom[0]   = @10;

id dictObj = custom[@1];
custom[@1] = @0;
18
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?