【问题标题】:Initializing realm globally causing a crash全局初始化领域导致崩溃
【发布时间】:2018-01-04 20:05:45
【问题描述】:

我有一个集成了领域的 swift 应用程序。我在 AppDelegate.swift 中全局声明领域,如下面的代码所示。当我执行这个应用程序时,我的应用程序在设备上运行良好,甚至在测试模式下。

问题:

在我提交应用程序后,Apple 审查委员会拒绝了该应用程序,并且象征性的崩溃日志指出了领域的初始化。

下面是代码,我可能做错了什么?

import UIKit
import CoreData
import Firebase
import UserNotifications
import Fabric

import RealmSwift

var uiRealm = try! Realm()

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate {

var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"
var tokenExists = false

let imageDb = DigitalFingerprint()
var uid: String!


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {


    #if DEVELOPMENT
        print("Development Mode Started")
        let filePath = Bundle.main.path(forResource: "GoogleService-Info", ofType: "plist")
        guard let fileopts = FirebaseOptions.init(contentsOfFile: filePath!)
            else {
                fatalError("Couldn't load config file")
        }
        FirebaseApp.configure(options: fileopts)
    #else
        print("Production Mode Started")
        FirebaseApp.configure()
    #endif

    Auth.auth().addStateDidChangeListener { (auth, user) in
        if (user != nil) {
            print("User is there")
            self.uid = KeychainWrapper.standard.string(forKey: KEY_UID)
        } else {
            print("user signed out")
            DB_URL.removeAllObservers()
            DispatchQueue.main.async {
                let storyboard = UIStoryboard(name: "Main", bundle: nil)
                let vc = storyboard.instantiateViewController(withIdentifier: "starts") as? BootVC
                var topRootViewController: UIViewController = (UIApplication.shared.keyWindow?.rootViewController)!
                while((topRootViewController.presentedViewController) != nil){
                    topRootViewController = topRootViewController.presentedViewController!
                }
                topRootViewController.present(vc!, animated: true, completion: nil)
            }
        }
    }

    if uid != nil {
        checkforAccess()
    }

    return true
}

下面是Real对象,DigitalFingerprint.swift

import Foundation
import RealmSwift
import UIKit

class DigitalFingerprint: Object {

@objc dynamic var imageData: Data? = nil
@objc dynamic var fid : String? = nil
@objc dynamic var uid : String? = nil
override static func primaryKey() -> String {
    return "uid"
}

}

extension DigitalFingerprint {

func writeToRealm(){
    try! uiRealm.write {
        uiRealm.add(self, update: true)
    }
}

func DeleteFromRealm(object: Results<DigitalFingerprint>){
    try! uiRealm.write {
        uiRealm.delete(object)
    }
}

}

苹果审查委员会收到的崩溃日志。 :

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note:  EXC_CORPSE_NOTIFY
Triggered by Thread:  0

Application Specific Information:
abort() called

Filtered syslog:
None found

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   libsystem_kernel.dylib          0x00000001830142e8 __pthread_kill + 8
1   libsystem_pthread.dylib         0x00000001831292f8 pthread_kill$VARIANT$mp + 396
2   libsystem_c.dylib               0x0000000182f83060 __abort + 152
3   libsystem_c.dylib               0x0000000182f82fc8 __abort + 0
4   libc++abi.dylib                 0x000000018271f068 __cxa_bad_cast + 0
5   libc++abi.dylib                 0x000000018271f1f8 default_terminate_handler+ 8696 () + 280
6   libobjc.A.dylib                 0x0000000182748820 _objc_terminate+ 34848 () + 140
7   SpotMi                          0x0000000100dc7d78 CLSTerminateHandler() + 1260920 (CLSException.mm:314)
8   libc++abi.dylib                 0x000000018273754c std::__terminate(void (*)+ 107852 ()) + 16
9   libc++abi.dylib                 0x00000001827375b8 std::terminate+ 107960 () + 60
10  Realm                           0x0000000101f94a00 realm::Realm::open_with_config(realm::Realm::Config const&, std::__1::unique_ptr<realm::Replication, std::__1::default_delete<realm::Replication> >&, std::__1::unique_ptr<realm::SharedGroup, std::__1::default_delete<realm::SharedGroup> >&, std::__1::unique_ptr<realm::Group, std::__1::default_delete<realm::Group> >&, realm::Realm*) + 985600 (memory:3006)
11  Realm                           0x0000000101f944e0 realm::Realm::Realm(realm::Realm::Config, std::__1::shared_ptr<realm::_impl::RealmCoordinator>) + 984288 (shared_realm.cpp:55)
12  Realm                           0x0000000101ed9658 realm::Realm::make_shared_realm(realm::Realm::Config, std::__1::shared_ptr<realm::_impl::RealmCoordinator>)::make_shared_enabler::make_shared_enabler(realm::Realm::Config, std::__1::shared_ptr<realm::_impl::RealmCoordinator>) + 218712 (shared_realm.hpp:304)
13  Realm                           0x0000000101ed94cc std::__1::shared_ptr<realm::Realm::make_shared_realm(realm::Realm::Config, std::__1::shared_ptr<realm::_impl::RealmCoordinator>)::make_shared_enabler> std::__1::shared_ptr<realm::Realm::make_shared_realm(realm::Realm::Config, std::__1::shared_ptr<realm::_impl::RealmCoordinator>)::make_shared_enabler>::make_shared<realm::Realm::Config, std::__1::shared_ptr<realm::_impl::RealmCoordinator> >(realm::Realm::Config&&,    std::__1::shared_ptr<realm::_impl::RealmCoordinator>&&) + 218316 (memory:2172)
14  Realm                           0x0000000101ed56a4 realm::_impl::RealmCoordinator::get_realm(realm::Realm::Config) + 202404 (realm_coordinator.cpp:229)
15  Realm                           0x0000000101f965f0 realm::Realm::get_shared_realm(realm::Realm::Config) + 992752 (shared_realm.cpp:250)
16  Realm                           0x0000000101f7016c +[RLMRealm realmWithConfiguration:error:] + 835948 (RLMRealm.mm:400)
17  RealmSwift                      0x00000001023911e4 Realm.init() + 152036 (Realm.swift:0)
18  RealmSwift                      0x0000000102391178 Realm.__allocating_init() + 151928 (Realm.swift:0)
19  SpotMi                          0x0000000100c9be14 globalinit_33_E3853139275E4567E078AE3BFE0165A3_func0 + 32276 (AppDelegate.swift:23)
20  libdispatch.dylib               0x0000000182e7ea14 _dispatch_client_callout + 16
21  libdispatch.dylib               0x0000000182e82240 dispatch_once_f$VARIANT$mp + 60
22  SpotMi                          0x0000000100cc2254 FeedVC.viewDidLoad() + 189012 (FeedVC.swift:84)
23  SpotMi                          0x0000000100cc2650 @objc FeedVC.viewDidLoad() + 190032 (FeedVC.swift:0)
24  UIKit                           0x000000018c9e3ae8 -[UIViewController loadViewIfRequired] + 1040
25  UIKit                           0x000000018c9e36c0 -[UIViewController view] + 28
26  UIKit                           0x000000018c9ea28c -[UIWindow    addRootViewControllerViewIfPossible] + 136
27  UIKit                           0x000000018c9e74ec -[UIWindow _setHidden:forced:] + 272
28  UIKit                           0x000000018ca563a0 -[UIWindow makeKeyAndVisible] + 48
29  UIKit                           0x000000018cc43d10 -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 3620
30  UIKit                           0x000000018cc48aa8 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1712
31  UIKit                           0x000000018cee42d4 __111-[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:]_block_invoke + 800
32  UIKit                           0x000000018d1bc12c +[_UICanvas _enqueuePostSettingUpdateTransactionBlock:] + 160
33  UIKit                           0x000000018cee3f38 -[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:] + 252
34  UIKit                           0x000000018cee4798 -[__UICanvasLifecycleMonitor_Compatability activateEventsOnly:withContext:completion:] + 732
35  UIKit                           0x000000018d6697d0 __82-[_UIApplicationCanvas _transitionLifecycleStateWithTransitionContext:completion:]_block_invoke + 260
36  UIKit                           0x000000018d669674 -[_UIApplicationCanvas _transitionLifecycleStateWithTransitionContext:completion:] + 448
37  UIKit                           0x000000018d3d72dc __125-[_UICanvasLifecycleSettingsDiffAction performActionsForCanvas:withUpdatedScene:settingsDiff:fromSettings:transitionContext:]_block_invoke + 220
38  UIKit                           0x000000018d5703dc _performActionsWithDelayForTransitionContext + 112
39  UIKit                           0x000000018d3d718c -[_UICanvasLifecycleSettingsDiffAction performActionsForCanvas:withUpdatedScene:settingsDiff:fromSettings:transitionContext:] + 252
40  UIKit                           0x000000018d1bb78c -[_UICanvas scene:didUpdateWithDiff:transitionContext:completion:] + 364
41  UIKit                           0x000000018cc471ec -[UIApplication workspace:didCreateScene:withTransitionContext:completion:] + 540
42  UIKit                           0x000000018d05cde8 -[UIApplicationSceneClientAgent scene:didInitializeWithEvent:completion:] + 364
43  FrontBoardServices              0x0000000185bc61f0 -[FBSSceneImpl _didCreateWithTransitionContext:completion:] + 364
44  FrontBoardServices              0x0000000185bceaf8 __56-[FBSWorkspace client:handleCreateScene:withCompletion:]_block_invoke_2 + 224
45  libdispatch.dylib               0x0000000182e7ea14 _dispatch_client_callout + 16
46  libdispatch.dylib               0x0000000182e86200    _dispatch_block_invoke_direct$VARIANT$mp + 288
47  FrontBoardServices              0x0000000185bfa7f8 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 36
48  FrontBoardServices              0x0000000185bfa49c -[FBSSerialQueue _performNext] + 404
49  FrontBoardServices              0x0000000185bfaa38 -[FBSSerialQueue _performNextFromRunLoopSource] + 56
50  CoreFoundation                  0x00000001834aa97c __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 24
51  CoreFoundation                  0x00000001834aa8fc __CFRunLoopDoSource0 + 88
52  CoreFoundation                  0x00000001834aa184 __CFRunLoopDoSources0 + 204
53  CoreFoundation                  0x00000001834a7d5c __CFRunLoopRun + 1048
54  CoreFoundation                  0x00000001833c7e58 CFRunLoopRunSpecific + 436
55  GraphicsServices                0x0000000185274f84 GSEventRunModal + 100
56  UIKit                           0x000000018ca4767c UIApplicationMain + 236
57  SpotMi                          0x0000000100c99b4c main + 23372 (SurpriseCell.swift:26)
58  libdyld.dylib                   0x0000000182ee456c start + 4

我也在我的 initialviewcontroller(Feedvc) 的 viewDidAppear() 中调用这个函数

我的程序的流程是

1.加载feedvc

  1. 如果用户为 nil

  2. 转到 bootVc(从应用委托调用)

我到底做错了什么?

另外,只在全局范围内声明一个 realm 类型的变量,然后在 didFinishLaunching() 中初始化变量会是更好的选择吗?

谢谢!

【问题讨论】:

  • 您说您看到了崩溃,但您没有提供有关崩溃性质的详细信息。请分享崩溃日志。
  • 感谢您的及时回复,我已经更新了我的问题
  • 这有什么?
  • 我是否在 App 委托中的 init() 中初始化领域,因为这不会给我带来任何崩溃。答案中讨论的另一个选项让我崩溃了。我现在该怎么办?

标签: ios swift realm appdelegate


【解决方案1】:

好吧,在类之外创建变量并不是一个好主意。尝试创建

var uiRealm = try! Realm()

在 AppDelegate 类中。并在其他类中使用(UIApplication.shared.delegate as! AppDelegate).uiRealm

【讨论】:

  • 我确实想过,但是,我需要通过不同的类调用uiRealm几次,每次都初始化实例是一个好习惯吗?这会导致内存问题
  • 您可以使用 AppDelegate 实例。示例:让 appDelegate = UIApplication.shared.delegate 为!应用委托;并使用 appDelegate.uiRealm。
  • 这就是我之后实施的。感谢您确认我的疑问。还有一件事,除了崩溃日志中的全局初始化之外,似乎还有其他问题吗?
  • 嘿,这给了我一个错误。当我从 Xcode 执行它时,它在设备中运行,但是当我在 beta 模式下运行它时它崩溃了。它在 Appdelegate 上给了我一个 found nil 异常
  • 我认为,如果您在每个类中创建领域实例,那就没问题了。因为据我所知,Realm 创建了一次它的实例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-17
  • 2022-06-22
相关资源
最近更新 更多