ios - 在 Objective C 中创建负数数组

标签 ios objective-c

我创建了一个由正数、负数和零组成的数组,但它将数组中的所有元素都视为正数。在代码中,positiveCount 为 6。如何在 Objective-C 中将负数放入数组中?

NSInteger positiveCount = 0;
NSInteger zeroCount = 0;
NSInteger negativeCount = 0;

NSArray *arr = [NSArray arrayWithObjects:@-4,@-3,@-9,@0,@4,@1, nil];

for (NSInteger i = 0; i < arr.count; i++){
    NSLog(@"%d",arr[i]);
    if (arr[i] > 0)
    {
        positiveCount += 1;
    } else if (arr[i] < 0){
        negativeCount += 1;
    } else {
        zeroCount += 1;
    }
}

NSLog(@"%d",positiveCount);

最佳答案

你数组中的元素不是数字,它们是NSNumber实例,也就是指针。指针始终为正:

for (NSNumber* number in arr) {
    NSInteger intValue = number.integerValue;
    NSLog(@"%d", intValue);

    if (intValue > 0) {
        positiveCount += 1;
    } else if (intValue < 0) {
        negativeCount += 1;
    } else {
        zeroCount += 1;
    }
}

关于ios - 在 Objective C 中创建负数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53894801/

相关文章:

iOS 核心蓝牙 : centralManager:didConnectPeripheral/didFailToConnectPeripheral: not getting called

ios - 无聊的 SSL 握手失败和复制 Identity Cred 时出错

ios - [UIApplication sharedApplication] 和 didFinishLaunchingWithOptions 的 application 参数有什么区别?

objective-c - 将照片上传到 Instagram 后,控件不会返回到应用程序

ios - 拉了一本字典 ios

ios - 按日期对自定义对象数组进行排序和分段

objective-c - 如何在 cocoa 中创建一个黑色圆角窗口

ios - 在 swift 中使用 objective c 协议(protocol)

ios - QuickLook ShouldOpenUrl 委托(delegate)方法未触发

ios - 从 CoreData 获取后,我可以重新排序具有 UITableView 日期属性的获取实体吗