码迷,mamicode.com
首页 > 移动开发 > 详细

iOS7 Programming Cookbook笔记

时间:2015-06-14 07:06:54      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

Chapter 1

Adding Object and Index Subscription Support

类似Dictionary和Array那种用下标来访问。

@interface Person : NSObject

@property (nonatomic, copy) NSString *firstName;
@property (nonatomic, copy) NSString *lastName;

// object subscription
- (id) objectForKeyedSubscript:(id
 
  
 
  
    )paramKey; - (void) setObject:(id)paramObject forKeyedSubscript:(id 
   
     )paramKey; // index subscription - (id) objectAtIndexedSubscript:(NSUInteger)paramIndex; - (void) setObject:(id)paramObject atIndexedSubscript:(NSUInteger)paramIndex; @end 
    
  
NSString *const kFirstNameKey = @“firstName”;
NSString *const kLastNameKey = @“lastName”;

@implementation Person

- (id) objectForKeyedSubscript:(id
 
  
 
  
    )paramKey{ NSObject 
   
     *keyAsObject = (NSObject 
    
      *)paramKey; if ([keyAsObject isKindOfClass:[NSString class]]){ NSString *keyAsString = (NSString *)keyAsObject; if ([keyAsString isEqualToString:kFirstNameKey] || [keyAsString isEqualToString:kLastNameKey]){ return [self valueForKey:keyAsString]; } } return nil; } - (void) setObject:(id)paramObject forKeyedSubscript:(id 
     
       )paramKey{ NSObject 
      
        *keyAsObject = (NSObject 
       
         *)paramKey; if ([keyAsObject isKindOfClass:[NSString class]]){ NSString *keyAsString = (NSString *)keyAsObject; if ([keyAsString isEqualToString:kFirstNameKey] || [keyAsString isEqualToString:kLastNameKey]){ [self setValue:paramObjectforKey:keyAsString]; } } } - (id) objectAtIndexedSubscript:(NSUInteger)paramIndex{ switch (paramIndex){ case 0:{ return self.firstName; break; } case 1:{ return self.lastName; break; } default:{ [NSException raise:@“Invalid index” format:nil]; } } return nil; } - (void) setObject:(id)paramObject atIndexedSubscript:(NSUInteger)paramIndex{ switch (paramIndex){ case 0:{ self.firstName = paramObject; break; } case 1:{ self.lastName = paramObject; break; } default:{ [NSException raise:@“Invalid index” format:nil]; } } } @end 
        
       
      
     
    
  

利用下标来操作对象。

Person *person = [Person new];
person[kFirstNameKey] = @“Tim”;
person[kLastNameKey] = @“Cook”;
NSString *firstNameByKey = person[kFirstNameKey];
NSString *lastNameByKey = person[kLastNameKey];

NSString *firstNameByIndex = person[0];
NSString *lastNameByIndex = person[1];

if ([firstNameByKey isEqualToString:firstNameByIndex] &&
    [lastNameByKey isEqualToString:lastNameByIndex]){
    NSLog(@“Success”);
} else {
    NSLog(@“Something is not right”);
}

iOS7 Programming Cookbook笔记

标签:

原文地址:http://my.oschina.net/leeming/blog/466429

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!