开发者

Understanding enumerations

开发者 https://www.devze.com 2023-03-02 08:13 出处:网络
Can someone fill in the rest of this enumeration line? I simply don\'t understand enumeration without an example. I\'m trying to arrange a table view by distance closest to the user. The code below is

Can someone fill in the rest of this enumeration line? I simply don't understand enumeration without an example. I'm trying to arrange a table view by distance closest to the user. The code below is the latitude portion, which is trying to enumerate through a plist of data (object at index 4 is the latitude stored as an NSNumber, clubLocation and myLocation are methods that return the location of the place and the user respectively). How does enumeration work and what does it return? An Array? How do I sync the array results with the other parts of the plist, like the name of the location? Many thanks.

-(NSArray *)distanceFromLat
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Data3" ofType:@"plist"];
    NSMutableDictionary *tempDictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:path];

    NSMutableArray *latitudeArray = [[NSMutableArray alloc] init];
    latitudeArray = [[tempDictionary objectForKey:@"Subtree"]objectAtIndex:4];

    NSEnumerator *enumLat = [latitudeArray objectEnumerator];
    id object;

    while ((object = [enumLat nextObject])) {
        [myLocation distance开发者_运维技巧FromLocation:clubLocation];
    }

}


why not use "fast enumeration"?

for (id latitude in latitudeArray) {
..
}

where you could replace id with the actual type of your latitude objects in the array. According to your comments that would be NSNumber.

The NSEnumerator style of enumeration works in just the same way. Each object in the loop is one object from the array, the array is enumerated so that each object it contains is accessed once. "Fast enumeration" is nicer because it is actually faster and conceptually it's easy to see what's going on - "for all x in y".

To get your latitudes sorted by distance from the user for table display you could create a mutable dictionary with a key made from the distance from the user (NSNumber) and an object which is the index of that latitude in your latitudeArray (NSNumber). Then use allKeys on that dictionary to get an array of all NSNumber keys, sort it with sortedArrayUsingSelector:@selector(compare:), and display is easy - the first table entry would be obtained by taking the first key in the sorted array, getting the index it keys in the dictionary and then using that index to retrieve the right latitude from latitudeArray.

0

精彩评论

暂无评论...
验证码 换一张
取 消