Getting array elements with valueForKeyPath

前端 未结 4 1112
眼角桃花
眼角桃花 2020-12-03 05:06

Is there any way to access an NSArray element with valueForKeyPath? Google\'s reverse geocoder service, for example, returns a very complex data s

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-03 05:35

    You can intercept the keypath in the object holding the NSArray.

    In your case the keypath would become Placemark0.address... Override valueForUndefinedKey; look for the index in the keypath; something like this:

    -(id)valueForUndefinedKey:(NSString *)key
    {
        // Handle paths like Placemark0, Placemark1, ...
        if ([key hasPrefix:@"Placemark"])
        {
            // Caller wants to access the Placemark array.
            // Find the array index they're after.
            NSString *indexString = [key stringByReplacingOccurrencesOfString:@"Placemark" withString:@""];
            NSInteger index = [indexString integerValue];
    
            // Return array element.
            if (index < self.placemarks.count)
                return self.placemarks[index];
        }
    
        return [super valueForUndefinedKey:key];
    }
    

    This works really well for model frameworks e.g. Mantle.

提交回复
热议问题