标签: foundation

给定数字时,将小数四舍五入到最接近的增量

我想将小数四舍五入到另一个数字的最接近的增量。例如,给定值2.23678301和增量0.0001,我想将其舍入为2.2367。有时增量可能类似于0.00022,在这种情况下,该值将向下舍入为2.23674

我尝试这样做,但有时结果不正确并且测试未通过:

extension Decimal {
    func rounded(byIncrement increment: Self) -> Self {
        var multipleOfValue = self / increment
        var roundedMultipleOfValue = Decimal()
        NSDecimalRound(&roundedMultipleOfValue, &multipleOfValue, 0, .down)
        return roundedMultipleOfValue * increment
    }
}

/// Tests

class DecimalTests: XCTestCase {
    func testRoundedByIncrement() {
        // Given
        let value: Decimal = 2.2367830187654

        // Then
        XCTAssertEqual(value.rounded(byIncrement: 0.00010000), 2.2367)
        XCTAssertEqual(value.rounded(byIncrement: 0.00022), 2.23674)
        XCTAssertEqual(value.rounded(byIncrement: 0.0000001), 2.236783)
        XCTAssertEqual(value.rounded(byIncrement: 0.00000001), 2.23678301) // XCTAssertEqual failed: ("2.23678301") is not equal to …
Run Code Online (Sandbox Code Playgroud)

decimal rounding foundation swift

1
推荐指数
1
解决办法
440
查看次数

如何使用 NSItemProvider 的新 Async loadItem 方法加载 URL?

DropDelegate将文件从桌面拖到我的应用程序时,我很难在 SwiftUI 中获取 fileURL 。

我正在使用异步 loadItem 调用,NSItemProvider该调用返回一个NSSecureCoding. 我以为我可以将结果转换为 NSURL 但它总是失败。

let url = try await (urlProvider
    .loadItem(forTypeIdentifier: UTType.url.identifier) as? NSURL
Run Code Online (Sandbox Code Playgroud)

如果我尝试强制转换,则会出现以下错误:

Could not cast value of type 'Foundation.__NSSwiftData' to 'NSURL'.
Run Code Online (Sandbox Code Playgroud)

我在代码中的其他地方成功地使用了相同的调用并转换为 NSDictionary。

这是在 Xcode 13.4、Swift 5 中。我在沙箱功能中具有对用户选择的文件的读取权限。

谁能帮助指出我做错了什么?谢谢。

foundation swift

1
推荐指数
1
解决办法
1977
查看次数

Mac OS X 10.6中的NSOperation是否有错误?

如果我NSOperation在发送之前发布了一个实例,-init我会得到一个segmentation fault.

我认为这是有效代码的原因:

  • Apple在其文档中做到了这一点.
  • Gnustep就是implementation of NSNumber这样做的,所以相当肯定这也是Apple的代码.(至少是.)
  • NSObjects -init不做任何事情,因此-release,属于NSObject应该在此之前工作.
// gcc -o test -L/System/Library/Frameworks -framework Foundation test.m

#import <Foundation/Foundation.h>

int main(int argc, char *argv[]) {
    NSOperation *theOperation = [NSOperation alloc];
    [theOperation release];
}
Run Code Online (Sandbox Code Playgroud)
  • 您怎么看?这是一个错误吗?
  • 你能告诉我一个具有相同行为的另一个类的例子吗?
  • 知道为什么会这样吗?

objective-c foundation nsoperation

0
推荐指数
1
解决办法
357
查看次数

Foundation.h出错

我在Linux(Ubuntu)中学习Objective-C,但是当我尝试编译需要Foundation头文件的应用程序时,我得到一个错误,说找不到该文件,但我已经安装了GNUstep开发包(gnustep-devel).这是我的代码:

// Fraction.h
#import <Foundation/NSObject.h>

@interface Fraction: NSObject {
    int numerator;
    int denominator;
}

- (void) print;
- (void) setNumerator: (int) n;
- (void) setDenominator: (int) d;
- (void) numerator;
- (void) denominator;
@end
Run Code Online (Sandbox Code Playgroud)

这是控制台日志:

ubuntu@eeepc:~$ gcc main.m -o frac -lobjc
In file included from main.m:3:
Fraction.h:2:26: error: objc/NSObject.h: No such file or directory
In file included from main.m:3:
Fraction.h:4: error: cannot find interface declaration for ‘NSObject’, superclass of ‘Fraction’
ubuntu@eeepc:~$
Run Code Online (Sandbox Code Playgroud)

我需要做什么?

objective-c gnustep foundation

0
推荐指数
1
解决办法
6380
查看次数

基础功能的内存管理指南

虽然基础类的内存管理是一致的并且有文档记录,但我很惊讶地发现(通过友好的EXC_BAD_ACCESS)基础函数,例如NSStringFromSelector()似乎返回指向常量存储的指针 - 这至少在函数的文档中没有提到.

这种行为是否记录在某处?有没有一致的指导方针?

cocoa objective-c foundation

0
推荐指数
1
解决办法
124
查看次数

我可以将同一个对象添加到两个不同的数组中吗?

这是有效的:

 NSObject anObject = [[NSObject alloc] init];
 [array1 addObject:anObject];
 [array2 addObject:anObject];
Run Code Online (Sandbox Code Playgroud)

我的钱是肯定的,因为我只是添加对同一个对象的引用,或者我错了吗?

cocoa object objective-c foundation nsarray

0
推荐指数
1
解决办法
381
查看次数

有关NSUndoManager的帮助

好的,所以我想在我的应用程序中添加撤消某些操作的功能。我本来打算用自己的协议或类似的东西来创建一种方法,但是后来我发现了NSUndoManager。我想使用内置的基础方式,但似乎无法弄清楚。我需要撤消多次掷骰子的操作,因此,如果我可以存储以前的掷骰,因为的对象NSArray可能是最好的。我可以使用NSMutableString,但最好使用数组。

然后,我知道您可以摇晃以撤消操作,但是我希望有一个按钮。这些一直给我带来最大的麻烦。我在下面列出了我的尝试。这些都不起作用。任何帮助,将不胜感激。

在viewDidLoad中:

undoManager = [[NSUndoManager alloc] init];
Run Code Online (Sandbox Code Playgroud)

然后在掷骰子的方法中,我尝试了:

   [[undoManager prepareWithInvocationTarget:self] undoButton];
    [[undoManager prepareWithInvocationTarget:self] 
    [[undoManager prepareWithInvocationTarget:self] setString:[NSString stringWithFormat:@"%i", dice1num]];

setStrings:[NSArray arrayWithObjects:[NSString stringWithFormat:@"%i", dice1num]
    [NSString stringWithFormat:@"%i", dice1num],
    [NSString stringWithFormat:@"%i", dice1num],
    [NSString stringWithFormat:@"%i", dice1num],
    [NSString stringWithFormat:@"%i", dice1num], nil]];
[[undoManager prepareWithInvocationTarget:@selector()];
[undoManager setActionName:@"A roll"];
Run Code Online (Sandbox Code Playgroud)

然后是链接到撤消按钮的IBAction:

-(IBAction)undoButton{
           [undoManager undo];
}
Run Code Online (Sandbox Code Playgroud)

提前致谢

iphone undo foundation nsundomanager

0
推荐指数
1
解决办法
1856
查看次数

哪些类可以用作NSDictionary中的键?

我们可以只使用NSString对象作为NSDictionary中的键吗?我们如何知道哪些对象可以使用哪些不可以使用?

iphone objective-c foundation ios

0
推荐指数
1
解决办法
467
查看次数

如何让NSTimer循环播放

我正在尝试学习NSTimer,使用Foundation和打印到控制台.任何人都可以告诉我我需要做些什么来让以下工作?它编译没有错误,但不激活我的startTimer方法 - 没有打印.

我的目标是让一个方法调用另一个方法来运行一些语句,然后在设定的时间后停止.

#import <Foundation/Foundation.h>

@interface MyTime : NSObject {
    NSTimer *timer;
}
- (void)startTimer;
@end

@implementation MyTime

- (void)dealloc {
    [timer invalidate];
    [super dealloc];
}

- (void)startTimer {
     timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(runTimer:) userInfo:nil repeats:YES];
}

- (void)runTimer:(NSTimer *)aTimer {
    NSLog(@"timer fired");
}
@end


int main(int argc, char *argv[]) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];


    MyTime *timerTest = [[MyTime alloc] init];
    [timerTest startTimer];

    [timerTest release];

    [pool release];
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

macos objective-c nstimer foundation

0
推荐指数
1
解决办法
1381
查看次数

NSMutableArray比较

我有两个NSMutableArray.一个数组由数据库中的记录组成,另一个数组由来自webservices的记录组成.

我想使用一个唯一的密钥比较数据库阵列中的每条记录与Web服务数组中的每条记录barcodeID.此外,如果barcodeID键是相同的,那么我想从数组中删除该项.这就像我正在更新我的数据库记录.如果我们从Web服务获得相同的记录,那么我不想插入它们.

请帮助我,我无法打破这个逻辑.

iphone collections objective-c foundation nsmutablearray

0
推荐指数
1
解决办法
142
查看次数

在命令行工具上使用 Swift URLSession 示例代码

我试图找出从命令行在 Swift 4 中发出 HTTP 请求的最简单方法。我从URLSession 编程指南中复制了这段代码,并添加了几个打印语句。我无法弄清楚为什么.dataTask没有执行。

print("Testing URLSession")
let sessionWithoutADelegate = URLSession(configuration: URLSessionConfiguration.default)
if let url = URL(string: "https://www.example.com/") {
    print("Encoded url \(url)")
    (sessionWithoutADelegate.dataTask(with: url) { (data, response, error) in
        print("Executing dataTask")
        if let error = error {
            print("Error: \(error)")
        } else if let response = response,
            let data = data,
            let string = String(data: data, encoding: .utf8) {
            print("Response: \(response)")
            print("DATA:\n\(string)\nEND DATA\n")
        }
    }).resume()
}
Run Code Online (Sandbox Code Playgroud)

目标是从 REST api 检索数据,但我什GET至无法发出简单的请求才能正常工作......

foundation nsurlsession swift

0
推荐指数
1
解决办法
4459
查看次数

Swift:将数组转换为String

如何将数组[Int]转换为例如保持元素之间逗号的字符串?如果我有一个like数组[1,2,3,4],我想收到一个String like "1, 2, 3, 4"

cocoa-touch foundation ios swift

-1
推荐指数
1
解决办法
5277
查看次数

如何用文字表达当前时间

我能够获得当前时间,现在我想用文字输出它。

let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let seconds = calendar.component(.second, from: date)
print("hours = \(hour):\(minutes):\(seconds)")
Run Code Online (Sandbox Code Playgroud)

输出

10:30

如何得到这个 -

现在是十点半了

foundation swift

-2
推荐指数
1
解决办法
466
查看次数