Search code examples
iphoneobjective-ciosin-app-purchase

how to sort products by price In App Purchases?


First,I got some products from IAP

-(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response  
{  
    [productDetailsList addObjectsFromArray: response.products];  
    [productDisplayTableView reloadData];  
}

How to put them in a uitableview sort by product price? thank you.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  
{  
    static NSString *GenericTableIdentifier = @"GenericTableIdentifier";  
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: GenericTableIdentifier];  
    if (cell == nil) {  
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                       reuseIdentifier:GenericTableIdentifier] autorelease];
    }   

    SKProduct *thisProduct = [productDetailsList objectAtIndex:row];
    NSUInteger row = [indexPath row];

    [button setTitle:localizedMoneyString forState:UIControlStateNormal];

    [cell.contentView addSubview:button];

    return cell; 
}

Solution

  • What you want to do is sort the NSArray prior to trying to read it. There are many options for sorting NSArray, most of them involve creating your own sorting method. You do something like:

    [productDetailList sortedArrayUsingFunction:intSort context:NULL];
    

    That will use your comparator method that you specify. The comparison method is used to compare two elements at a time and should return NSOrderedAscending if the first element is smaller than the second, NSOrderedDescending if the first element is larger than the second, and NSOrderedSame if the elements are equal. Each time the comparison function is called, it’s passed context as its third argument. This allows the comparison to be based on some outside parameter, such as whether character sorting is case-sensitive or case-insensitive, but this doesn't matter in your case. The function you have to implement would look like this:

    NSInteger intSort(id num1, id num2, void *context)
    

    For more information of the above method take a look at the documentation, it give you an example.

    So you can sort the array like this or you always have the choice of sorting the array every time you add something. So every time you add an object you do the sorting yourself and make sure to put it in the right location to keep the array always sorted.

    Depending on what you want, I would say keeping the array constantly sorted on insertion time is the best option, so you don't have to waste time while building the view by sorting the array. To do it like this would be simple, every time you enter something into the array, you iterate through the array until you find an object with a price larger than the one you want to enter, then you insert the object at the location before that entry.