数组排序、写入文件和GCD

- (NSString *)fileLocation{
//获取文件路径(返回值是一个数组),其实就只有一个值
 NSArray *folders = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
    if ([folders count] == 0) {
        return nil;
    }
    NSString *documentsFolder = folders[0];
    return [documentsFolder stringByAppendingString:@"list2.txt"];
}

- (BOOL)hasFileAlreadyBeenCreated{  //判断文件是否存在
    BOOL result = NO;
    NSFileManager *fileManger = [[NSFileManager alloc] init];
    if ([fileManger fileExistsAtPath:[self fileLocation]]) {
        return YES;
    }
    return result;
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(concurrentQueue, ^{  //开启一个异步操作,gcd队列是concurrentQueue
        NSInteger numberOfValueRequired = 10;
        if ([self hasFileAlreadyBeenCreated] == NO) { //是否文件已存在,
            dispatch_sync(concurrentQueue, ^{  //不存在
                NSMutableArray *arrayOfRandomNumbers = [[NSMutableArray alloc] initWithCapacity:numberOfValueRequired];
                NSInteger counter = 0;
                for (counter = 0; counter < numberOfValueRequired; counter++) {
                    unsigned int randomNumber = arc4random()%((unsigned int)RAND_MAX + 1);
                    [arrayOfRandomNumbers addObject:[NSNumber numberWithUnsignedInt:randomNumber]];
                }
                [arrayOfRandomNumbers writeToFile:[self fileLocation] atomically:YES];
            });
        }
    __block NSMutableArray *randomNumbers = nil;
    dispatch_sync(concurrentQueue, ^{  
        if ([self hasFileAlreadyBeenCreated]) {  //文件存在
            randomNumbers = [[NSMutableArray alloc] initWithContentsOfFile:[self fileLocation]];
            NSLog(@"Self Location is %@",[self fileLocation]);
            NSArray * sortArray = [randomNumbers sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
                NSNumber *number1 = (NSNumber *)obj1;
                NSNumber *number2 = (NSNumber *)obj2;
                return [number1 compare:number2];
            }];
            NSLog(@"kkkk %@",sortArray);
            [sortArray writeToFile:[self fileLocation] atomically:YES];
        }
    });
 }
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@4,@7,@2,@8,@1,@7,@6,@9, nil ];
   // NSMutableArray *mutaleArray = [[NSMutableArray alloc] initWithArray:array];
    NSArray *sortArray = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSNumber *N1 = (NSNumber *)obj1;
        NSNumber *N2 = (NSNumber *)obj2;
        return [N1 compare:N2];
        /*if(obj1 > obj2){  //第二种方法
            return NSOrderedAscending;
          }else{
            return NSOrderedDecending
          }
        */
 }];
    for (int i = 0; i < sortArray.count; i++) {
        NSLog(@"Number is %@",sortArray[i]);
    }
}

 
  
  
  
  

NSSortDescriptor 指定用于对象数组排序的对象的属性。

如果是Employee对象需要按照name来排序,就生成下面的descriptor

NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:name ascending:YES];

如果需要多个排序,比如先按name排序,再按入职日期排序。那就创建两个descriptor

NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:hireDate ascending:YES];

两个descriptor放到数组里一起传给需要排序的数组。


如果对象就是NSString,就是字符串数组排序,那更简单了,sortdescriptor的key直接指定为nil,就直接排序对象,而不是对象的某一个属性了。

   NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES];

  NSArray *descriptors = [NSArray arrayWithObject:descriptor];

   NSArray *myDataArray = [NSArray arrayWithObjects:@"what", @"xero", @"highligth", @"mountain", @"Victory", @"Balance", nil];

  NSArray *resultArray = [myDataArray sortedArrayUsingDescriptors:descriptors];

  NSLog(@"%@", resultArray);


NSArray 使用sortedArrayUsingDescriptors,返回排序好的数组。

NSMutableArray可以直接使用sortUsingDescriptors,对数组本身排序。





你可能感兴趣的:(数组排序、写入文件和GCD)