2017-02-14 4 views
0

У меня есть два класса, а именно ViewController и BViewController. Класс BViewController имеет название, адрес и рейтинг.Сортировка массива пользовательских объектов в Objective-C

Ниже приведен код для ViewController.m

Как я могу идти о упорядочивание объектов в массиве таким образом, что они упорядочены по рейтингу по возрастанию? Кроме того, как мне отображать их в представлении?

- (void)viewDidLoad { 

     [super viewDidLoad]; 

    BViewController *b=[[BViewController alloc]init]; 
     [email protected]"x"; 
     [email protected]"bangalore"; 
     [email protected]; 

    BViewController *c=[[BViewController alloc]init]; 
     [email protected]"y"; 
     [email protected]"bangalore"; 
     [email protected]; 

    BViewController *d=[[BViewController alloc]init]; 
     [email protected]"z"; 
     [email protected]"bangalore"; 
     [email protected]; 

    BViewController *e=[[BViewController alloc]init]; 
     [email protected]"abc"; 
     [email protected]"bangalore"; 
     [email protected]; 

    BViewController *f=[[BViewController alloc]init]; 
     [email protected]"xyz"; 
     [email protected]"bangalore"; 
     [email protected]; 
    } 

ответ

1

Ваш массив

NSMutableArray *arrMain = [NSMutableArray arrayWithObjects:b, c, d, e ,f, nil]; 

Сейчас Сортировать на основе Рейтинг ключа

NSArray *arrResult; 
arrResult = [arrMain sortedArrayUsingComparator:^NSComparisonResult(id a, id b) { 
    NSNumber *first = [(BViewController*)a rating]; 
    NSNumber *second = [(BViewController*)b rating]; 

    NSComparisonResult result = [first compare:second]; 
    return result; 
}]; 

Испытано

Надежда, это поможет.
Благодаря

+0

Можете ли вы сказать мне, что, предположим, взять в storyBoard, например textField или ярлык, чтобы отобразить результаты, новичок, так что я не понимаю, как это происходит! – taj

+0

@taj Для ввода введите UITextfields. UIButton для Sort Array Hit и UILabel для отображения значений результата. –

+0

эй, можно сказать, как я могу видеть вывод на консоли? потому что если я поставлю NSLog (@ "% @", arrResult); я получаю некоторый вывод, например, «», «», «», «», «». Не понимаю, почему это идет так – taj

1

Apple, имеет API, чтобы сделать то, что вы хотите в элегантный способ:

NSMutableArray *yourArray = [NSMutableArray arrayWithObjects:b, c, d, e ,f, nil]; 
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"rating" ascending:YES]; 
[yourArray sortUsingDescriptors:@[sortDescriptor]]; 

Ваш массив теперь сортируется красиво.