简体   繁体   中英

How to find available memory in iPhone programmatically?

我想知道如何通过 Objective-C 在 iPhone 中以编程方式找到可用内存?

You can get physical memory with the following:

NSLog(@"physical memory: %d", [NSProcessInfo processInfo].physicalMemory);

Available memory is going to be not something you can nail down to a hard number, since the os will kill off background apps for you as needed to give the foreground app more memory, along with clearing file caches etc. Assuming you're doing this to optimize your own caching, you could build your cache size based on physical memory and guess how much you should use. For instance, on an old 128m iphone 3g, your entire app would only get maybe 10-15megs of ram before it got killed, where a brand new 1024meg iphone5 is going to allow you hundreds of megabytes of ram before the os decides to kill you.

See memory in devices at http://en.wikipedia.org/wiki/List_of_iOS_devices

You can use the Mach call host_info(host, flavor, host_info, host_info_count) . If you call it with flavor=HOST_BASIC_INFO , the buffer host_info points to is filled with a struct host_basic_info , what looks like that:

struct host_basic_info {
    integer_t               max_cpus;               /* max number of CPUs possible */
    integer_t               avail_cpus;             /* number of CPUs now available */
    natural_t               memory_size;            /* size of memory in bytes, capped at 2 GB */
    cpu_type_t              cpu_type;               /* cpu type */
    cpu_subtype_t           cpu_subtype;            /* cpu subtype */
    cpu_threadtype_t        cpu_threadtype;         /* cpu threadtype */
    integer_t               physical_cpu;           /* number of physical CPUs now available */
    integer_t               physical_cpu_max;       /* max number of physical CPUs possible */
    integer_t               logical_cpu;            /* number of logical cpu now available */
    integer_t               logical_cpu_max;        /* max number of physical CPUs possible */
    uint64_t                max_mem;                /* actual size of physical memory */
}

From this structure, you can get the memory size.

Swift 5

Your Ram Size in Bytes:

let totalRam = ProcessInfo.processInfo.physicalMemory

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM