如何将CLLocationManager方法转换为iOS目标c中的块

时间:2016-09-20 05:33:52

标签: ios objective-c objective-c-blocks cllocationmanager appdelegate

我在将CCLocationManager方法转换为块时遇到问题。 我的CLLocationManager方法如下所示:

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"didUpdateToLocation: %@", newLocation);
    }
    else{NSLog(@"current location is nil");};
}

我正在尝试将此方法转换为块,但很难尝试这样做。一种新的客观c和ios开发。

我正在做的是这样的事情:

double (^getSpeed)(*CLLocation, *CLLocation) = ^(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
        {
            NSLog(@"didUpdateToLocation: %@", newLocation);
            CLLocation *currentLocation = newLocation;
            mSpeed = currentLocation.speed;
            }
            else{NSLog(@"current location is nil");};
            return mSpeed;
        };

但它给出了一个错误,说它需要在块的第一行中有一个表达式。这是什么意思? 任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:0)

你可以这样试试,

// 1.在.h文件中声明方法和块,如下所示

    typedef void (^currentLocation)(CLLocation *currentLocation);
    // Create property using typedef
    @property (strong) currentLocation objBlock;
    - (void)updateCurrentLocation:(currentLocation)completionBlock;

// 2.在委托方法中就像这样

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *location = [locations lastObject];
    _objBlock(location);
    [locManager stopUpdatingLocation];
    locManager = nil;
}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error {
    NSLog(@"%@",[error localizedDescription]);
}

- (void)updateCurrentLocation:(currentLocation)completionBlock {
    _objBlock = completionBlock;
}

// 3.调用就像这样,当调用block时,block会被触发。

    [self updateCurrentLocation:^(CLLocation *currentLocation) {
        NSLog(@"%@", currentLocation);
    }];