4

He encontrado un código en Objective-c para que calcule la carga de la cpu pero esta en Objective-c y no se objective-c si no Swift he intentado pasarlo a Swift pero sin ningún resultado. Tampoco se como pasarlo a una función o algo y llamarla desde Swift.

PROBLEMA RESUELTO. En el proyecto de swift crear un nuevo fichero.m que lo tenéis que enlazar en el bridging-Header.h y llamar desde el archivo swift load() y todo funcionara.

CODIGO RESEUELTO

#import <Foundation/Foundation.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include <mach/mach.h>
#include <mach/processor_info.h>
#include <mach/mach_host.h>
    processor_info_array_t cpuInfo, prevCpuInfo;
mach_msg_type_number_t numCpuInfo, numPrevCpuInfo;
unsigned numCPUs;
NSTimer *updateTimer;
NSLock *CPUUsageLock;

void load() {
    int mib[2U] = { CTL_HW, HW_NCPU };
    size_t sizeOfNumCPUs = sizeof(numCPUs);
    int status = sysctl(mib, 2U, &numCPUs, &sizeOfNumCPUs, NULL, 0U);
    if(status)
        numCPUs = 1;

        CPUUsageLock = [[NSLock alloc] init];

    natural_t numCPUsU = 0U;
    kern_return_t err = host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &numCPUsU, &cpuInfo, &numCpuInfo);
    if(err == KERN_SUCCESS) {
        [CPUUsageLock lock];

        for(unsigned i = 0U; i < numCPUs; ++i) {
            float inUse, total;
            if(prevCpuInfo) {
                inUse = (
                         (cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_USER]   - prevCpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_USER])
                         + (cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_SYSTEM] - prevCpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_SYSTEM])
                         + (cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_NICE]   - prevCpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_NICE])
                         );
                total = inUse + (cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_IDLE] - prevCpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_IDLE]);
            } else {
                inUse = cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_USER] + cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_SYSTEM] + cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_NICE];
                total = inUse + cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_IDLE];
            }

            NSLog(@"Core: %u Usage: %f",i,inUse / total);
        }
        [CPUUsageLock unlock];

        if(prevCpuInfo) {
            size_t prevCpuInfoSize = sizeof(integer_t) * numPrevCpuInfo;
            vm_deallocate(mach_task_self(), (vm_address_t)prevCpuInfo, prevCpuInfoSize);
        }

        prevCpuInfo = cpuInfo;
        numPrevCpuInfo = numCpuInfo;

        cpuInfo = NULL;
        numCpuInfo = 0U;
    } else {
        NSLog(@"Error!");
    }
}
6
  • parece que objectivec2swift tiene una restricción de 1 KB, en la salida
    – jasilva
    el 20 ene. 2016 a las 19:10
  • no se si esta pregunta entra dentro de la tematica de es SO, quizas con la etiqueta de revision de codigo. Saludos el 20 ene. 2016 a las 19:11
  • Angel, requiere una reputación de 150 poner la etiqueta SO
    – Bogdan
    el 20 ene. 2016 a las 19:13
  • no pero creo que si entra si la pregunta principal es ¿como llamar codigo de objetive-c desde switf?, creo que yo entendi mal y pense que querias generar el mismo codigo pero en switf. Saludos el 20 ene. 2016 a las 19:15
  • quizas estos link lo puedan ayudar, mientras -> developer.apple.com/library/prerelease/ios/documentation/Swift/… y este otro stackoverflow.com/questions/24002369/… quizas ayude tanto a usted o para crear una repuesta. Saludos el 20 ene. 2016 a las 19:18

1 respuesta 1

3

No es necesario que conviertas el código a Swift. Puedes utilizar Objective-C directamente en tu proyecto. A continuación te explico como lo he hecho yo.

Primero de todo crea una clase llamada "CPUInfoManager" y selecciona como lenguaje Objective-C

introducir la descripción de la imagen aquí

Cuando se haya creado, te preguntará si quieres crear un "bridging header". ¡Créalo!

introducir la descripción de la imagen aquí

Ahora busca el fichero del bridging, por ejemplo "MyProject-Bridging-Header.h" y añade la siguiente línea

#import "CPUInfoManager.h"

A continuación, el fichero de interfaz (.h) déjalo como sigue

//
//  CPUInfoManager.h
//  TestChart
//
//  Created by mhergon on 20/1/16.
//  Copyright © 2016 Marc Hervera. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface CPUInfoManager : NSObject

- (NSDictionary *)getCoresInfo;

@end

Y el de implementación (.m) tal que así

//
//  CPUInfoManager.m
//  TestChart
//
//  Created by mhergon on 20/1/16.
//  Copyright © 2016 Marc Hervera. All rights reserved.
//

#import "CPUInfoManager.h"

#include <sys/sysctl.h>
#include <sys/types.h>
#include <mach/mach.h>
#include <mach/processor_info.h>
#include <mach/mach_host.h>

@implementation CPUInfoManager

processor_info_array_t cpuInfo, prevCpuInfo;
mach_msg_type_number_t numCpuInfo, numPrevCpuInfo;
unsigned numCPUs;
NSTimer *updateTimer;
NSLock *CPUUsageLock;

- (instancetype)init
{
    self = [super init];
    if (self) {

        int mib[2U] = { CTL_HW, HW_NCPU };
        size_t sizeOfNumCPUs = sizeof(numCPUs);
        int status = sysctl(mib, 2U, &numCPUs, &sizeOfNumCPUs, NULL, 0U);
        if(status)
            numCPUs = 1;

        CPUUsageLock = [[NSLock alloc] init];

    }
    return self;
}

- (NSDictionary *)getCoresInfo {

    natural_t numCPUsU = 0U;
    kern_return_t err = host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &numCPUsU, &cpuInfo, &numCpuInfo);
    if(err == KERN_SUCCESS) {
        [CPUUsageLock lock];

        NSMutableDictionary *cpuInfoResult = [NSMutableDictionary new];

        for(unsigned i = 0U; i < numCPUs; ++i) {
            float inUse, total;
            if(prevCpuInfo) {
                inUse = (
                         (cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_USER]   - prevCpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_USER])
                         + (cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_SYSTEM] - prevCpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_SYSTEM])
                         + (cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_NICE]   - prevCpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_NICE])
                         );
                total = inUse + (cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_IDLE] - prevCpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_IDLE]);
            } else {
                inUse = cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_USER] + cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_SYSTEM] + cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_NICE];
                total = inUse + cpuInfo[(CPU_STATE_MAX * i) + CPU_STATE_IDLE];
            }

            NSString *coreKey = [NSString stringWithFormat:@"%u", i];
            cpuInfoResult[coreKey] = [NSNumber numberWithFloat:inUse / total];
        }
        [CPUUsageLock unlock];

        if(prevCpuInfo) {
            size_t prevCpuInfoSize = sizeof(integer_t) * numPrevCpuInfo;
            vm_deallocate(mach_task_self(), (vm_address_t)prevCpuInfo, prevCpuInfoSize);
        }

        prevCpuInfo = cpuInfo;
        numPrevCpuInfo = numCpuInfo;

        cpuInfo = NULL;
        numCpuInfo = 0U;

        return cpuInfoResult;

    } else {

        NSLog(@"Error!");
        return nil;

    }

}

@end

Ahora solo te queda utilizar esta nueva clase en una función Swift, por ejemplo

func updateValues() {

    // Get Cores info
    let result = CPUInfoManager().getCoresInfo()
    print(result)

}

Resumiendo, puedes mezclar Objective-C y Swift sin problemas.

2
  • gracias, como podría sumar los valores que me devuelve el if y que me de el % de 100
    – Bogdan
    el 20 ene. 2016 a las 21:10
  • Te contesto en el otro hilo que has creado
    – mhergon
    el 20 ene. 2016 a las 21:13

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.