如果iOS设备内存不足,我们可以通过编程方式检查吗?

时间:2017-06-21 06:36:16

标签: ios memory memory-management memory-leaks out-of-memory

我的情况是必须将大量事务上传到服务器。我使用在NSManagedObjectContext队列上执行阻止的performBlock: NSManagedObjectContext方法异步地完成了这项工作。所以在async-block中我怎么能观察到低内存警告!而不是观察我想确定设备是否有足够的可用内存,然后只上传数据。否则,如果它的内存不足,则等到发生内存不足然后恢复上传作业。

1 个答案:

答案 0 :(得分:0)

您可以在上传数据之前检查iOS设备的可用磁盘空间,以避免内存不足。

+(uint64_t)getFreeDiskspace {

    uint64_t totalSpace = 0;
    uint64_t totalFreeSpace = 0;
    NSError *error = nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];

    if (dictionary) {
        NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];
        NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
        totalSpace = [fileSystemSizeInBytes unsignedLongLongValue];
        totalFreeSpace = [freeFileSystemSizeInBytes unsignedLongLongValue];
        NSLog(@"Memory Capacity of %llu MiB with %llu MiB Free memory available.", ((totalSpace/1024ll)/1024ll), ((totalFreeSpace/1024ll)/1024ll));
    } else {
        NSLog(@"Error Obtaining System Memory Info: Domain = %@, Code = %ld", [error domain], (long)[error code]);
    }
    return totalFreeSpace;
}