开发者

Comparing an NSString with NSNumber in the string

Someone else designed this class to have an NSString for an ID (I don't know why to be honest). So, some objects have @"" for their ID (blank), some have @"id12345" or something to that effect. I want to sort by the number for my UITableView

First thing I did was use:

stringByReplacingOccurrencesOfString:@"id" withString:@""];

so I could get the number. I'm sure there is a convenience method to get the NSInteger from the NSString, but I just haven't looked it up yet. Then I kind of got stuck because

since my object, Markers, has a NSString of this ID, how do I sort by the number without replacing the original value in the object? My initial thoughts were to get the id number from the nsstring and sort. However, I didn't want to replace the original nsstring either. The class I have is basically just display开发者_Python百科ing and sorting the data.

This is what I have so far:

- (NSArray *)sortByID:(NSArray *)sortDescriptors {
    for (Marker *m in self.MarkersList) {
        if (![m.id length] == 0) {
            NSString *str = [m.id stringByReplacingOccurrencesOfString:@"id" withString:@""];
        // don't know what to do here....
        }
    }
    return [self.MarkersList sortedArrayUsingDescriptors:sortDescriptors];
}


I don't really see why you're using sortDescriptors for here, since you're only sorting by numbers.

I'd use a comparator block (assuming you're on iOS 4 or above) and do it like below:

- (NSArray *)sortByID {

 NSArray* orderedList = [self.MarkersList 
                         sortedArrayUsingComparator:^(id obj1, id obj2) 
                     {
                        Marker* m1 = (Marker*) obj1;
                        Marker* m2 = (Marker*) obj2;

                        NSString* str;

                        str = [m1.id stringByReplacingOccurrencesOfString:@"id"
                               withString:@""];
                        NSInteger num1 = [str integerValue];

                        str = [m2.id stringByReplacingOccurrencesOfString:@"id" 
                               withString:@""];
                        NSInteger num2 = [str integerValue];

                        NSComparisonResult result;
                        if (num1 < num2) {
                            result = NSOrderedAscending;
                        } else if (num1 == num2 ) {
                            result = NSOrderedSame;
                        } else {
                            result = NSOrderedDescending;
                        }

                        return result;
                    }];


return orderedList;
}


So if you are guaranteed that all your strings look like id######, then after you replace the id from string you can use strings intValue method to get the int value of the string, then just compare the two ints...hope this helps

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜