@interface NSArray (SubscriptKey) @end @implementation NSArray (SubscriptKey) - (id)valueForUndefinedKey:(NSString *)key { if ([key isEqualToString:@"size"]) { return @(self.count); } else if ([key isEqualToString:@"first"]) { return self.firstObject; } else if ([key isEqualToString:@"last"]) { return self.lastObject; } else { NSInteger idx = [key integerValue]; if(idx < 0) { idx = self.cout + idx; } if (idx>=0 && idx<self.cout) return self[idx]; } else { return [super valueForUndefinedKey:key]; } } } @end
NSArray *arr = @[@"1",@"2", @"3"]; NSDictionary *dict = @{@"k":arr}; NSString *a = [dict valueForKeyPath:@"k.@last"]; NSString *b = [dict valueForKeyPath:@"k.@2"]; NSString *b = [dict valueForKeyPath:@"k.@-2"];
随意转载,注明出处:https://doorxp.com/?id=70