gpt4 book ai didi

ios - 我如何使用带整数的 NSRange 来简化我的代码?

转载 作者:可可西里 更新时间:2023-11-01 03:39:34 25 4
gpt4 key购买 nike

我刚刚开始学习 Objective-C 并制作了一个小指南针应用程序,当它落入一系列标题时会显示方向。它工作得很好,但我想知道是否有使用 NSRange 编写它的更简洁的方法。看了很多之后,似乎 NSRange 更多地用于字符串函数而不是数字。

我试图将 NSRange 的实例作为我的起点,以使其更简洁,但我无法找到查找数字是否落在 NSRange .

我是否在正确的轨道上,或者我是否使它变得比需要的更冗长?

提前致谢..

这是我尝试缩短代码的失败起点:

// If heading falls within this range, then display "S" for south    
NSRange eastenRange = NSMakeRange (80, 100);
NSRange southernRange = NSMakeRange (170, 190);
etc...

这是我当前的代码(工作正常):

- (void)locationManager:(CLLocationManager *)manager 
didUpdateHeading:(CLHeading *)newHeading
{
// Define and display the heading
NSNumber *theHeading = [NSNumber numberWithInt:[newHeading trueHeading]];
[headingLabel setText:[NSString stringWithFormat:@"%@°", theHeading]];

// Define the range of directions
NSNumber *northLowerRange = [NSNumber numberWithInt:10];
NSNumber *northUpperRange = [NSNumber numberWithInt:350];

NSNumber *eastLowerRange = [NSNumber numberWithInt:80];
NSNumber *eastUpperRange = [NSNumber numberWithInt:100];

NSNumber *southLowerRange = [NSNumber numberWithInt:170];
NSNumber *southUpperRange = [NSNumber numberWithInt:190];

NSNumber *westLowerRange = [NSNumber numberWithInt:260];
NSNumber *westUpperRange = [NSNumber numberWithInt:280];


// If the heading falls within the correct ranges, then display the direction
if ([northLowerRange compare:theHeading] == NSOrderedDescending || [northUpperRange compare:theHeading] == NSOrderedAscending)
[directionLabel setText:@"N"];
else if ([eastLowerRange compare:theHeading] == NSOrderedAscending && [eastUpperRange compare:theHeading] == NSOrderedDescending)
[directionLabel setText:@"E"];
else if ([southLowerRange compare:theHeading] == NSOrderedAscending && [southUpperRange compare:theHeading] == NSOrderedDescending)
[directionLabel setText:@"S"];
else if ([westLowerRange compare:theHeading] == NSOrderedAscending && [westUpperRange compare:theHeading] == NSOrderedDescending)
[directionLabel setText:@"W"];
else
[directionLabel setText:@"-"];

}

最佳答案

聚会迟到了,但我相信以下内容会起作用并利用范围:

NSRange easternRange = NSMakeRange (80, 20); 
NSRange southernRange = NSMakeRange (170, 20);

NSInteger heading = 92;
if (NSLocationInRange(heading,easternRange)) {
NSLog(@"Heading Easterly.");
} else if (NSLocationInRange(heading,southernRange)) {
NSLog(@"Heading southerly.");
}

等等等

关于ios - 我如何使用带整数的 NSRange 来简化我的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4139085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com