开发者

How sort an NSMutableArray?

I am trying to sort an NSMutableArray for t开发者_Go百科hat I am using comparer selector;

- (NSComparisonResult)compare:(Product *)someObject {
    return [self.Price compare:someObject.Price];
}

HomeProducts = [HomeProducts sortedArrayUsingSelector:@selector(compare:)];

I want to sort the same array and donot want to assign to other array.

request for member 'Price' in something not a structure or union .... 

its not recognizing self.Price.


Assuming that compare: is in the Product class then you need to use the console to investigate further.

When the exception occurs, what are the values of self and someObject - I bet that one of them is either not a Product or something that's been released (I think the latter!)

When the crash occurs, you can check the values of self and someObject in the console like this :

po self
po someObject

(or use the gui to the left of the console).


EDIT Answer to comment :

sortedArrayUsingSelector: returns an NSArray, HomeProducts is an NSMutableArray. Try this instead :

HomeProducts = [[HomeProducts sortedArrayUsingSelector:@selector(compare:)] mutableCopy];


How you use it, compare: should be a method of Product. Try to use a block instead:

[homeProducts sortUsingComparator: ^NSComparisonResult (id obj1, id obj2)
{
    return [[obj1 Price] compare: [obj2 Price]];
} 

or, if Price is a simple type, use:

[homeProducts sortUsingComparator: ^NSComparisonResult (id obj1, id obj2)
{
    return ([obj1 Price] < [obj2 Price]) ? NSOrderedAscending :
           ([obj1 Price] > [obj2 Price]) ? NSOrderedDescending :
                                           NSOrderedSame;
} 

FWIW, it is customary to give instance variables, variables, properties, etc. a name starting with a lower case character, and only types start with an uppercase letter.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜