как использовать sortUsingFunction: context - PullRequest
1 голос
/ 15 ноября 2009

appdata.items - это NSMutableArray.

Я не собираю этот код. Код ошибки: «prop.173 имеет неполный тип».

NSInteger compareInfo(id aInfo1, id aInfo2, void *context){
  NSDate* info1 = [aInfo1 objectAtIndex:2];
  NSDate* info2 = [aInfo2 objectAtIndex:2];
  return [info1 compare:info2];
}

-(void)saveData{
  NSData* data = [[NSMutableData alloc] init];
  appdata.items = [appdata.items sortUsingFunction:compareInfo context:NULL];
  NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
  [archiver encodeObject:appdata forKey:DATAKEY];
  [archiver finishEncoding];
  [data writeToFile:[self dataFilePath] atomically:YES];
  [archiver release];
  [data release];
}

Ответы [ 3 ]

8 голосов
/ 17 февраля 2011

Вот код, который может вам помочь (я трачу довольно много времени на то, чтобы заставить его работать, документ не очень полезен)

Он вычисляет расстояние между объектом POI и объектом currentLocation и заказывает объект POI от ближайшего к самому дальнему из этого местоположения

NSInteger compareDistance(id num1, id num2, void *context) 
{

int retour;
// fist we need to cast all the parameters
CLLocation* location = context;
POI* param1 = num1;
POI* param2 = num2;

// then we can use them as standard ObjC objects
CLLocation* locationCoordinates = [[CLLocation alloc] initWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
CLLocation* locationPOI1 = [[CLLocation alloc] initWithLatitude:param1.coords.latitude longitude:param1.coords.longitude];
CLLocation* locationPOI2 = [[CLLocation alloc] initWithLatitude:param2.coords.latitude longitude:param2.coords.longitude];
CLLocationDistance distance1 = [locationPOI1 distanceFromLocation:locationCoordinates];
CLLocationDistance distance2 = [locationPOI2 distanceFromLocation:locationCoordinates];

//make the comparaison
if (distance1 < distance2)
    retour = NSOrderedAscending;
else if (distance1 > distance2)
    retour = NSOrderedDescending;
else
    retour = NSOrderedSame;

[locationCoordinates release];
[locationPOI1 release];
[locationPOI2 release];
return retour;

 }

 -(void) orderByProximityFromLocation:(CLLocationCoordinate2D) coordinates
 {
CLLocation* currentLocation = [[CLLocation alloc] initWithLatitude:coordinates.latitude longitude:coordinates.longitude];
[listOfPOI sortUsingFunction:compareDistance context:currentLocation];
[currentLocation release];

 }
3 голосов
/ 15 ноября 2009

Метод sortUsingFunction:context: предназначен для NSMutableArray, а не NSArray, который сортирует содержимое изменяемого массива. Вам нужен метод sortedArrayUsingFunction:context:, который вернет отсортированный массив, который вы можете назначить, как вы сейчас пытаетесь сделать.

Если, конечно, элементы не являются NSMutableArray, в этом случае вы можете вызвать sortUsingFunction:context:, но так как он ничего не возвращает, вы не назначаете его элементам.

2 голосов
/ 15 ноября 2009

Эта ссылка: http://www.cocoadev.com/index.pl?SortUsingSelector Есть несколько примеров работающей функции sortUsingFunction. (прокрутите мимо материала sortUsingSelector).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...