done = (*slash == ‘\0’);
*slash = ‘\0’;
if (stat(path, &sb) != 0) {
// 执行创建文件夹的操作, C 中无 mkdirs 的操作, 需要一个一个文件夹的创建
if (errno != ENOENT || mkdir(path, 0777) != 0) {
MMKVWarning("%s : %s", path, strerror(errno));
return false;
}
}
// 若非文件夹, 则说明为非法路径
else if (!S_ISDIR(sb.st_mode)) {
MMKVWarning("%s: %s", path, strerror(ENOTDIR));
return false;
}
*slash = ‘/’;
}
return true;
}
以上是 Native 层创建文件路径的通用代码, 逻辑很清晰
好的, 文件目录创建好了之后, Native 层的初始化操作便结束了, 接下来看看 MMKV 实例构建的过程
三. 实例化
public class MMKV implements SharedPreferences, SharedPreferences.Editor {
@Nullable
public static MMKV mmkvWithID(String mmapID, int mode, String cryptKey, String relativePath) {
…
// 执行 Native 初始化, 获取句柄值
long handle = getMMKVWithID(mmapID, mode, cryptKey, relativePath);
if (handle == 0) {
return null;
}
// 构建一个 Java 的壳对象
return new MMKV(handle);
}
private native static long
getMMKVWithID(String mmapID, int mode, String cryptKey, String relativePath);
// jni
private long nativeHandle;
private MMKV(long handle) {
nativeHandle = handle;
}
}
可以看到 MMKV 实例构建的主要逻辑通过 getMMKVWithID 方法实现, 看它内部做了什么
// native-bridge.cpp
namespace mmkv {
MMKV_JNI jlong getMMKVWithID(
JNIEnv *env, jobject, jstring mmapID, jint mode, jstring cryptKey, jstring relativePath) {
MMKV *kv = nullptr;
if (!mmapID) {
return (jlong) kv;
}
// 获取独立存储 id
string str = jstring2string(env, mmapID);
bool done = false;
if (cryptKey) {
// 获取秘钥
string crypt = jstring2string(env, cryptKey);
if (crypt.length() > 0) {
if (relativePath) {
// 获取相对路径
string path = jstring2string(env, relativePath);
// 通过 mmkvWithID 函数获取一个 MMKV 的对象
kv = MMKV::mmkvWithID(str, DEFAULT_MMAP_SIZE, (MMKVMode) mode, &crypt, &path);
} else {
kv = MMKV::mmkvWithID(str, DEFAULT_MMAP_SIZE, (MMKVMode) mode, &crypt, nullptr);
}
done = true;
}
}
…
// 强转成句柄, 返回到 Java
return (jlong) kv;
}
}
可以看到最终通过 MMKV::mmkvWithID 函数获取到 MMKV 的对象
// MMKV.cpp
MMKV *MMKV::mmkvWithID(
const std::string &mmapID, int size, MMKVMode mode, string *cryptKey, string *relativePath) {
if (mmapID.empty()) {
return nullptr;
}
SCOPEDLOCK(g_instanceLock);
// 1. 通过 mmapID 和 relativePath, 组成最终的 mmap 文件路径的 key
auto mmapKey = mmapedKVKey(mmapID, relativePath);
// 2. 从全局缓存中查找
auto itr = g_instanceDic->find(mmapKey);
if (itr != g_instanceDic->end()) {
MMKV *kv = itr->second;
return kv;
}
// 3. 创建缓存文件
if (relativePath) {
// 根据 mappedKVPathWithID 获取 mmap 的最终文件路径
// mmapID 使用 md5 加密
auto filePath = mappedKVPathWithID(mmapID, mode, relativePath);
// 不存在则创建一个文件
if (!isFileExist(filePath)) {
if (!createFile(filePath)) {
return nullptr;
}
}
…
}
// 4. 创建实例对象
auto kv = new MMKV(mmapID, size, mode, cryptKey, relativePath);
// 5. 缓存这个 mmapKey
(*g_instanceDic)[mmapKey] = kv;
return kv;
}
mmkvWithID 函数的实现流程非常的清晰, 这里我们主要关注一下实例对象的创建流程
// MMKV.cpp
MMKV::MMKV(
const std::string &mmapID, int size, MMKVMode mode, string *cryptKey, string *relativePath)
: m_mmapID(mmapedKVKey(mmapID, relativePath))
// 拼装文件的路径
, m_path(mappedKVPathWithID(m_mmapID, mode, relativePath))
// 拼装 .crc 文件路径
, m_crcPath(crcPathWithID(m_mm