Watch app starts with error clientIdentifier for interfaceControllerID not found - ios

I'm having a smartwatch app on watchos2. The app always worked but now when it starts I immediately get this error:
Lop_WatchKit_Extension[17535:7854201] *********** ERROR -[SPRemoteInterface _interfaceControllerClientIDForControllerID:] clientIdentifier for interfaceControllerID:447E0002 not found
I found some topics here on stackoverflow but nothing solved the problem.

In my case, this was due to a retain cycle in one InterfaceController of mine.
If you get the logs similar to:
[default] -[SPRemoteInterface
_interfaceControllerClientIDForControllerID:]:0000: ComF: clientIdentifier for interfaceControllerID:XXXXXXXX not found
&/or...
[default] _SendRecordedValues:000: ComF:<-Plugin controller ID
XXXXXXXX has no client identifier
First, figure out which InterfaceController has the controller ID XXXXXXXX.
Have this in awake(withContext:)
override func awake(withContext context: Any?) {
//...
if let id = self.value(forKey: "_viewControllerID") as? NSString {
let strClassDescription = String(describing: self)
print("\(strClassDescription) has the Interface Controller ID \(id)")
}
//...
}
This logs:
[Target.Classname: 0xYYYYYYYY] has the Interface Controller ID
XXXXXXXX
Once you identify the InterfaceController causing these logs, you can continue to debug.
It could be different in your case but in mine I had created a retain cycle with self in one of my closures within which took awhile to locate but I eventually broke the retain cycle with a [weak self] capture.
Basically, the error logs appear when an InterfaceController is trying to execute some code but it has already been released.
What I already had:
DispatchQueue.main.async {
self.doSomethingThatDoesSomethingAsync()
}
What I fixed:
DispatchQueue.main.async { [weak self] in
self?.doSomethingThatDoesSomethingAsync()
}

If you use didSet on any IBOutlets it will also throw this error in the logs.
class MyInterfaceController: WKInterfaceController {
#IBOutlet var myLabel: WKInterfaceLabel! {
didSet {
myLabel.setTitle("Test")
}
}

How #nickromano sad, it's happens when you use didSet with IBOutlets. Cause it's calls before awake(withContext context: Any?)
We can suppress this error if wrap it in DispatchQueue.main.async
#IBOutlet var statusLabel: WKInterfaceLabel! {
didSet {
DispatchQueue.main.async {
self.statusLabel.setHidden(true)
}
}

This has happened to me a few times and more times than not, it is because of a timer that is still firing in a just-previously dismissed WKInterfaceController that I did not catch.
Best thing to do aside from comparing ID's like in #staticVoidMan's answer is to read the call stack. In my case I was able to identify that the old timer was still firing based off these hints:
8 Foundation 0x00007fff214be867 __NSFireTimer + 67
9 CoreFoundation 0x00007fff207a8e3f __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 20
10 CoreFoundation 0x00007fff207a8912 __CFRunLoopDoTimer + 926
Here is the original call stack (for reference):
<MyApp.InterfaceController: 0x7fb3e4d2d020> has the Interface Controller ID 1EB00002
2021-05-26 14:44:06.632758-0600 MyApp WatchKit Extension[73392:3546879] [default] -[SPRemoteInterface _interfaceControllerClientIDForControllerID:]:2464: ComF: clientIdentifier for interfaceControllerID:1EB00007 not found. callStack:(
0 WatchKit 0x00007fff38d1a268 -[SPRemoteInterface _interfaceControllerClientIDForControllerID:] + 220
1 WatchKit 0x00007fff38d1bfff __54+[SPRemoteInterface setController:key:property:value:]_block_invoke + 340
2 WatchKit 0x00007fff38d12323 spUtils_dispatchAsyncToMainThread + 30
3 WatchKit 0x00007fff38d1be60 +[SPRemoteInterface setController:key:property:value:] + 179
4 WatchKit 0x00007fff38d057af -[WKInterfaceObject _sendValueChanged:forProperty:] + 706
5 WatchKit 0x00007fff38d2a5f8 -[WKInterfaceObject _setImage:forProperty:] + 50
6 MyApp WatchKit Extension 0x000000010955531d $s26MyApp_WatchKit_Extension25ActivityIndicatorDelegateC06handleE5TimeryyF + 813
7 MyApp WatchKit Extension 0x000000010955537a $s26MyApp_WatchKit_Extension25ActivityIndicatorDelegateC06handleE5TimeryyFTo + 42
8 Foundation 0x00007fff214be867 __NSFireTimer + 67
9 CoreFoundation 0x00007fff207a8e3f __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 20
10 CoreFoundation 0x00007fff207a8912 __CFRunLoopDoTimer + 926
11 CoreFoundation 0x00007fff207a7ec5 __CFRunLoopDoTimers + 265
12 CoreFoundation 0x00007fff207a2546 __CFRunLoopRun + 1949
13 CoreFoundation 0x00007fff207a18be CFRunLoopRunSpecific + 567
14 GraphicsServices 0x00007fff25b49fd3 GSEventRunModal + 139
15 UIKitCore 0x00007fff43290f24 -[UIApplication _run] + 917
16 UIKitCore 0x00007fff43295c0b UIApplicationMain + 101
17 WatchKit 0x00007fff38d0de65 WKExtensionMain + 800
18 libdyld.dylib 0x00007fff20202db5 start + 1
19 ??? 0x0000000000000001 0x0 + 1
)

Have you changed the name of your module? If this is the case then you have to go through your storyboard and update it manually for all the Interfaces you have.
Edit with steps to fix:
Go to the storyboard and for each interface open the Identity inspector, then delete what's in Module and press enter, the new module should get auto-filled.

Related

Run-time crash BridgeFromObjectiveC when format date string to Foundation.Date

We've got kind of a weird bug in our app that only one user encounters so far (out of thousands) and I can't figure it out how to solve this, so maybe you can help me further.
It's about the following crash (run-time):
#0. Crashed: com.apple.main-thread
0 libswiftFoundation.dylib 0x10e51ec _TZFV10Foundation4Date36_unconditionallyBridgeFromObjectiveCfGSqCSo6NSDate_S0_ + 68
1 XXX 0x14d804 specialized static Loader._save(NSDictionary, Double, moc : NSManagedObjectContext) -> () (Loader.swift:149)
2 XXX 0x14d804 specialized static Loader._save(NSDictionary, Double, moc : NSManagedObjectContext) -> () (Loader.swift:149)
3 XXX 0x14286c static Loader.(registerUser(NSManagedObjectContext) -> ()).(closure #1) (Loader.swift)
4 Alamofire 0x5aea58 specialized DataRequest.(response<A where ...> (queue : DispatchQueue?, responseSerializer : A, completionHandler : (DataResponse<A.SerializedObject>) -> ()) -> Self).(closure #1).(closure #1) (ResponseSerialization.swift)
5 libdispatch.dylib 0x1b911797 _dispatch_call_block_and_release + 10
6 libdispatch.dylib 0x1b911783 _dispatch_client_callout + 22
7 libdispatch.dylib 0x1b915d05 _dispatch_main_queue_callback_4CF + 902
8 CoreFoundation 0x1c1ffd69 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 8
9 CoreFoundation 0x1c1fde19 __CFRunLoopRun + 848
10 CoreFoundation 0x1c1510ef CFRunLoopRunSpecific + 470
11 CoreFoundation 0x1c150f11 CFRunLoopRunInMode + 104
12 GraphicsServices 0x1d8fbb41 GSEventRunModal + 80
13 UIKit 0x214d5e83 UIApplicationMain + 150
14 XXX 0xb7b1c main (AppDelegate.swift:26)
15 libdyld.dylib 0x1b93e4eb start + 2
Line 149 of Loader.swift is:
let createDate : Foundation.Date = dateFormatter.date(from: eventCreated)!
It looks like it's an internal problem inside libswiftFoundation.dylib.
I've researched a lot about this problem and the only thing I could find on this was from Apple:
Some Objective-C methods in the SDKs may incorrectly annotate or assume a type to be nonnull rather than nullable. A type that Swift treats as a struct, such as NSURL (Foundation.URL) or NSDate (Foundation.Date), results in a run-time crash in a method with a name like bridgeFromObjectiveC; in other cases, it can lead to crashes or undefined behavior in user code. If you identify such a method, please file a report at bugreport.apple.com. As a workaround, add a trampoline function in Objective-C with the correct nullability annotations. For example, the following function will allow you to call FileManager'senumerator(at:includingPropertiesForKeys:options:errorHandler:) method with an error handler that accepts nil URLs:
https://developer.apple.com/library/content/releasenotes/DeveloperTools/RN-Xcode/Chapters/Introduction.html (under known issues)
With an example that looks like this:
static inline NSDirectoryEnumerator<NSURL *> * _Nullable
fileManagerEnumeratorAtURL(NSFileManager *fileManager, NSURL * _Nonnull url, NSArray<NSURLResourceKey> * _Nullable keys, NSDirectoryEnumerationOptions options, BOOL (^ _Nullable errorHandler)(NSURL * _Nullable errorURL, NSError * _Nonnull error)) {
return [fileManager enumeratorAtURL:url includingPropertiesForKeys:keys options:options errorHandler:^(NSURL * _Nonnull errorURL, NSError * _Nonnull error) {
return errorHandler(errorURL, error);
}];
}
I've already submitted a bug report for this issue, but still haven't got a response from Apple (after 7 days). I think this could fix the problem, but I'm not sure on how to port the given trampoline function (example) to a valid/working NSDate/DateFormatter version. Does someone know more about this problem and/or got it solved?

*** Terminating app due to uncaught exception 'NSGenericException', reason: 'Start date cannot be later in time than end date!'

I am using Alamofire and after several hours of my app running on the simulator I got a crash with this error.
*** Terminating app due to uncaught exception 'NSGenericException', reason: 'Start date cannot be later in time than end date!'
I got this stack trace in console:
*** First throw call stack:
(
0 CoreFoundation 0x0000000111186d4b __exceptionPreprocess + 171
1 libobjc.A.dylib 0x0000000110be821e objc_exception_throw + 48
2 Foundation 0x00000001107f0e3c -[_NSConcreteDateInterval dealloc] + 0
3 CFNetwork 0x00000001131a18e8 -[__NSCFURLSessionTaskMetrics _initWithTask:] + 868
4 CFNetwork 0x00000001131a1497 -[NSURLSessionTaskMetrics _initWithTask:] + 100
5 CFNetwork 0x0000000112f77bc7 -[__NSCFURLLocalSessionConnection _tick_finishing] + 351
6 libdispatch.dylib 0x00000001128e3978 _dispatch_call_block_and_release + 12
7 libdispatch.dylib 0x000000011290d0cd _dispatch_client_callout + 8
8 libdispatch.dylib 0x00000001128eae17 _dispatch_queue_serial_drain + 236
9 libdispatch.dylib 0x00000001128ebb4b _dispatch_queue_invoke + 1073
10 libdispatch.dylib 0x00000001128ee385 _dispatch_root_queue_drain + 720
11 libdispatch.dylib 0x00000001128ee059 _dispatch_worker_thread3 + 123
12 libsystem_pthread.dylib 0x0000000112cbc736 _pthread_wqthread + 1299
13 libsystem_pthread.dylib 0x0000000112cbc211 start_wqthread + 13
)
libc++abi.dylib: terminating with uncaught exception of type NSException
Did someone get the similar crash?
Thanks
I had the same crash and did some research today and found this:
http://www.openradar.me/28301343
It looks Apple fixed the issue in iOS 10.2. just thought it may help you!
Yes I just got the same exact crash. It happened in a background thread and it seems to have to do with making a URL session network request. I wonder if it's some sort of multithreading bug having to do with the fact that I'm making two network requests at the same time. I'm using Alamofire as well but not sure if the bug lies in Alamofire or in Apple's code. I've been unable to reproduce it as of now. Maybe you can figure out how to reproduce it and then file an issue in Apple's bug radar or in the Alamofire GitHub repo.
This is a bug in Apple's NSURLSessionTaskMetrics code and happens during a network request when the user's clock gets moved far enough backwards that the request start timestamp is after the request end timestamp. This is reproducible using a network debugging proxy and manually adjusting the clock, and only occurs from iOS 10.0 up to but not including iOS 10.2
If you're using Alamofire, and you don't need NSURLSessionTaskMetrics, you can work around this by using a custom SessionDelegate for your SessionManager and overriding the responds(to aSelector..) function e.g:
class MySessionDelegate: Alamofire.SessionDelegate {
override public func responds(to aSelector: Selector) -> Bool {
let result: Bool = super.responds(to: aSelector)
if #available(iOS 10.2, *) {
// NSURLSessionTaskMetrics date crash is fixed
return result
} else if #available(iOS 10.0, *) {
// NSURLSessionTaskMetrics date crash is not fixed, turn off metric collection
if aSelector == #selector(self.urlSession(_:task:didFinishCollecting:)) {
return false
} else {
return result
}
} else {
// NSURLSessionTaskMetrics doesn't exist
return result
}
}
}
If you're using the default SessionManager (e.g. calling Alamofire.request(...)) you can create your own SessionManager instead in order to use your custom SessionDelegate:
let sessionManager: Alamofire.SessionManager = {
let configuration: URLSessionConfiguration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
return Alamofire.SessionManager(configuration: configuration, delegate: MySessionDelegate(), serverTrustPolicyManager: nil)
}()
And now instead of calling Alamofire.request(...) you'd call sessionManager.request(...)
I have been struggling with this problem in an os x application for the last few months and have found a workaround.
Background:
Like the OP am using Alamofire to request JSON data via a Timer to send requests several times per second. The data comes in as expected however I get random crashes at irregular intervals with the same message as the OP i.e. Start date cannot be later in time than end date! etc etc.
Solution:
Rather than send Alamofire requests at a regular interval I added some logic which checks for a return of the previous request before sending the next one. This completely eliminated the random crashes.
Hope it helps :)
#thierryb

Realm object has been deleted or invalidated

When I start my app, I perform an API call to see whether there's new data available. The data is stored in my local Realm database, and some of it is displayed in the initial table view controller.
Once the API call is finished, I check if some conditions are met that require me to delete a bunch of the previous data from the database and then create new objects. However, when I delete the old data, my app crashes with the following exception:
2015-08-06 11:56:32.057 MSUapp[19754:172864] *** Terminating app due to uncaught exception 'RLMException', reason: 'Object has been deleted or invalidated.'
*** First throw call stack:
(
0 CoreFoundation 0x000000010660cc65 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x00000001083bdbb7 objc_exception_throw + 45
2 Realm 0x0000000105b78e95 _ZL17RLMVerifyAttachedP13RLMObjectBase + 85
3 Realm 0x0000000105b7878d _ZL10RLMGetLinkP13RLMObjectBasemP8NSString + 29
4 Realm 0x0000000105b7c23e ___ZL17RLMAccessorGetterP11RLMProperty15RLMAccessorCodeP8NSString_block_invoke_12 + 46
5 MSUapp 0x0000000105764867 _TFFC6MSUapp29FavoriteLeaguesViewController18generateLeagueListFS0_FT_T_U_FTCS_6LeagueS1__Sb + 39
6 MSUapp 0x00000001057648eb _TTRXFo_oC6MSUapp6LeagueoS0__dSb_XFo_iS0_iS0__dSb_ + 27
7 libswiftCore.dylib 0x0000000108674ae2 _TFSs14_insertionSortUSs21MutableCollectionType_USs13GeneratorType__Ss22BidirectionalIndexType_Ss18_SignedIntegerType_Ss33_BuiltinIntegerLiteralConvertible____FTRQ_GVSs5RangeQQ_5Index_RFTQQQ_9Generator7ElementS7__Sb_T_ + 1570
8 libswiftCore.dylib 0x0000000108676682 _TFSs14_introSortImplUSs21MutableCollectionType_USs13GeneratorType__Ss21RandomAccessIndexType_Ss18_SignedIntegerType_Ss33_BuiltinIntegerLiteralConvertible_Ss16SignedNumberType_S3_____FTRQ_GVSs5RangeQQ_5Index_RFTQQQ_9Generator7ElementS8__SbSi_T_ + 1250
9 libswiftCore.dylib 0x0000000108676172 _TFSs10_introSortUSs21MutableCollectionType_USs13GeneratorType__Ss21RandomAccessIndexType_Ss18_SignedIntegerType_Ss33_BuiltinIntegerLiteralConvertible_Ss16SignedNumberType_S3_____FTRQ_GVSs5RangeQQ_5Index_FTQQQ_9Generator7ElementS8__Sb_T_ + 1058
10 libswiftCore.dylib 0x00000001085ec947 _TFSs4sortUSs21MutableCollectionType_USs13GeneratorType__Ss21RandomAccessIndexType_Ss18_SignedIntegerType_Ss33_BuiltinIntegerLiteralConvertible_Ss16SignedNumberType_S3_____FTRQ_FTQQQ_9Generator7ElementS6__Sb_T_ + 471
11 libswiftCore.dylib 0x00000001086a8d9e _TPA__TFFSa4sortU__FRGSaQ__FFTQ_Q__SbT_U_FRGVSs26UnsafeMutableBufferPointerQ__T_ + 222
12 libswiftCore.dylib 0x00000001086a8e18 _TPA__TTRG0_R_XFo_lGVSs26UnsafeMutableBufferPointerq___dT__XFo_lGS_q___iT__42 + 56
13 libswiftCore.dylib 0x00000001085f7fda _TFSa30withUnsafeMutableBufferPointerU__fRGSaQ__U__FFRGVSs26UnsafeMutableBufferPointerQd___Q_Q_ + 522
14 libswiftCore.dylib 0x00000001085f7db4 _TFSa4sortU__fRGSaQ__FFTQ_Q__SbT_ + 132
15 MSUapp 0x0000000105761709 _TFC6MSUapp29FavoriteLeaguesViewController18generateLeagueListfS0_FT_T_ + 1097
16 MSUapp 0x000000010576354b _TFC6MSUapp29FavoriteLeaguesViewController27numberOfSectionsInTableViewfS0_FCSo11UITableViewSi + 59
17 MSUapp 0x00000001057635fa _TToFC6MSUapp29FavoriteLeaguesViewController27numberOfSectionsInTableViewfS0_FCSo11UITableViewSi + 58
18 UIKit 0x000000010737cac3 -[UITableViewRowData _updateNumSections] + 84
19 UIKit 0x000000010737d4b4 -[UITableViewRowData invalidateAllSections] + 69
20 UIKit 0x00000001071c873b -[UITableView _updateRowData] + 217
21 UIKit 0x00000001071de2b7 -[UITableView noteNumberOfRowsChanged] + 112
22 UIKit 0x00000001071dd9f5 -[UITableView reloadData] + 1355
23 MSUapp 0x00000001057647c6 _TFFC6MSUapp29FavoriteLeaguesViewController11viewDidLoadFS0_FT_T_U_FTO10RealmSwift12NotificationCS1_5Realm_T_ + 166
24 RealmSwift 0x0000000105f37210 _TFF10RealmSwift41rlmNotificationBlockFromNotificationBlockFFT12notificationOS_12Notification5realmCS_5Realm_T_bTSSCSo8RLMRealm_T_U_FTSSS2__T_ + 224
25 RealmSwift 0x0000000105f372af _TTRXFo_oSSoCSo8RLMRealm_dT__XFdCb_dCSo8NSStringdS__dT__ + 111
26 Realm 0x0000000105c0645a -[RLMRealm sendNotifications:] + 986
27 Realm 0x0000000105c068e6 -[RLMRealm commitWriteTransaction] + 262
28 Realm 0x0000000105c06a48 -[RLMRealm transactionWithBlock:] + 120
29 RealmSwift 0x0000000105f34250 _TFC10RealmSwift5Realm5writefS0_FFT_T_T_ + 176
30 MSUapp 0x00000001056d46db _TZFC6MSUapp14DatabaseHelper23removeForSportAndSeasonfMS0_FTCS_5Sport6seasonSS_T_ + 603
31 MSUapp 0x0000000105710d22 _TFFFC6MSUapp11AppDelegate14loadRemoteDataFS0_FT_T_U_FGSaCS_5Sport_T_U_FGSaCS_6League_T_ + 866
32 MSUapp 0x0000000105710dc7 _TTRXFo_oGSaC6MSUapp6League__dT__XFo_iGSaS0___iT__ + 23
33 MSUapp 0x00000001057103d1 _TPA__TTRXFo_oGSaC6MSUapp6League__dT__XFo_iGSaS0___iT__ + 81
34 MSUapp 0x000000010575de90 _TTRXFo_iGSaC6MSUapp6League__iT__XFo_oGSaS0___dT__ + 32
35 MSUapp 0x000000010575ddeb _TFZFC6MSUapp9APIHelper11loadLeaguesFMS0_FTSi18shouldWriteToRealmSb10completionGSqFGSaCS_6League_T___T_U_FCSo6NSDataT_ + 2763
36 MSUapp 0x00000001056f4a0e _TTSf2n_n_n_n_n_d_i_n_n_n___TFFC6MSUapp14JSONDataSource18loadRemoteJsonDataFS0_FTSSCS_19GETParameterBuilderFCSo6NSDataT__T_U_FTCSo12NSURLRequestGSqCSo17NSHTTPURLResponse_GSqS2__GSqCSo7NSError__T_ + 2302
37 MSUapp 0x00000001056f2d59 _TPA__TTSf2n_n_n_n_n_d_i_n_n_n___TFFC6MSUapp14JSONDataSource18loadRemoteJsonDataFS0_FTSSCS_19GETParameterBuilderFCSo6NSDataT__T_U_FTCSo12NSURLRequestGSqCSo17NSHTTPURLResponse_GSqS2__GSqCSo7NSError__T_ + 249
38 Alamofire 0x00000001059e7599 _TTRXFo_oCSo12NSURLRequestoGSqCSo17NSHTTPURLResponse_oGSqCSo6NSData_oGSqCSo7NSError__dT__XFo_oS_oGSqS0__iGSqS1__oGSqS2___dT__ + 25
39 Alamofire 0x00000001059e7461 _TFFFC9Alamofire7Request8responseFDS0_US_18ResponseSerializer___FT5queueGSqCSo8NSObject_18responseSerializerQ_17completionHandlerFTCSo12NSURLRequestGSqCSo17NSHTTPURLResponse_GSqQ0__GSqCSo7NSError__T__DS0_U_FT_T_U_FT_T_ + 737
40 Alamofire 0x00000001059e690e _TPA__TFFFC9Alamofire7Request8responseFDS0_US_18ResponseSerializer___FT5queueGSqCSo8NSObject_18responseSerializerQ_17completionHandlerFTCSo12NSURLRequestGSqCSo17NSHTTPURLResponse_GSqQ0__GSqCSo7NSError__T__DS0_U_FT_T_U_FT_T_ + 206
41 Alamofire 0x00000001059a89d7 _TTRXFo__dT__XFdCb__dT__ + 39
42 libdispatch.dylib 0x000000010938b186 _dispatch_call_block_and_release + 12
43 libdispatch.dylib 0x00000001093aa614 _dispatch_client_callout + 8
44 libdispatch.dylib 0x0000000109392a1c _dispatch_main_queue_callback_4CF + 1664
45 CoreFoundation 0x00000001065741f9 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
46 CoreFoundation 0x0000000106535dcb __CFRunLoopRun + 2043
47 CoreFoundation 0x0000000106535366 CFRunLoopRunSpecific + 470
48 GraphicsServices 0x000000010cc17a3e GSEventRunModal + 161
49 UIKit 0x00000001070f08c0 UIApplicationMain + 1282
50 MSUapp 0x000000010570f857 main + 135
51 libdyld.dylib 0x00000001093df145 start + 1
52 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
This call stack lets me assume, that it's because of my write access in FavoriteLeaguesViewController's generateLeagueList method. The following is its body:
var favorites = FavoritesHelper.sharedInstance.favoriteLeagues
favorites.sort { $0.sport < $1.sport }
for favorite in favorites {
// Add to array, which we can later use for cellForRowAtIndexPath
}
favorites is of the type [League], where League is a Realm Object. I'd assume the exception occurs because I'm accessing properties of the League objects, which have been deleted from the Realm database in the mean time (because the API call that has been started in the AppDelegate is now finished).
My question then is: How can I prevent this from happening? How can I make sure that there's no more writing/reading-access to any of the League objects prior to deleting them?
You can check if an object has been deleted from the Realm by calling object.invalidated -- if it returns true, then it has been deleted or the Realm has manually invalidated.
I got a really nice way to catch a RLMException within Swift.
Currently Swift doesn't show where a RLMException happened.
In Realm/RLMUtil.mm:266, there is the definition for RLMException.
If you change the code to generate a swift error,
Xcode now can show you where the exception occurred.
Now it is a part of Swift.
// Realm/RLMUtil.mm:266
static NSException *RLMException(NSString *reason, NSDictionary *additionalUserInfo) {
// add some code to generate a swift error. E.g. division-by-zero.
int a = 0;
if (reason == nil) {
a = 1;
}
NSLog(#"calculating 1 / %d = %f", a, 1 / a);
... remainder of the original code...
}
I've just place breakpoint inside method:
// Realm/RLMUtil.mm:193
static NSException *RLMException(NSString *reason, NSDictionary *additionalUserInfo) {
// ...
}
And on left panel you can check stack trace, here you can find where error throws.
The issue was in my FavoritesHelper class. It had both a favoriteLeagueIDs and favoriteLeagues property. I always set both of them and used the IDs for internal usage and the other property for whenever I want some data from these leagues.
This meant, that all favorite leagues were constantly referenced by the favoriteLeagues property (of the type [League]), thus crashing the app when I wanted to fetch them after they're invalidated.
What I've done to fix this, was to change the property favoriteLeagues to a computed property as follows:
var favoriteLeagues: [League] {
get {
var leagues = [League]()
for id in favoriteLeagueIDs {
if let league = realm.objectForPrimaryKey(League.self, key: id) {
leagues.append(league)
}
}
return leagues
}
}
Now the leagues are no longer referenced and just get loaded from the database when I need to read them. Invalidated or deleted objects don't get loaded because of the if let statement (the Realm.objectForPrimaryKey(:key:) method returns nil in such a case).
I was unable to place breakpoints within the Realm framework itself as others suggested, but instead placed an exception breakpoint on my entire project:
This allowed me to catch a proper stack trace when the exception was thrown, and find my bug.
you can calling isInvalidated or invalidated to judge the object is invalid (YES) or not (NO).
you can also write a a custom method to define what is real invalidate
look for the document ,we will see a property:
/**
Indicates if the object can no longer be accessed because it is now invalid.
An object can no longer be accessed if the object has been deleted from the Realm that manages it, or
if `invalidate` is called on that Realm.
*/
#property (nonatomic, readonly, getter = isInvalidated) BOOL invalidated;
the invalidated is readonly but what does isInvalidated mean?
it is equals to - (BOOL)invalidated { return invalidated; }
it means that you can write a a custom method to define what is real invalidate you want.
Try to create the element on realm instead of add
So:
try! realm.write {
realm.add(...)
}
Replace with:
try! realm.write {
realm.create(...)
}
And then after the delete operation realm should work as expected!
In my experience, if you trying to use target object (which you wanna delete) after delete, application will crash.
If you wanna trigger some code blocks after removing realm object, just trying to trigger that block right before the object removing in the memory. Trying to usage that object after removed from memory, will make some problem and will crash the app.
For example:
try! realm.write {
print("deleted word: \(targetObject.word)")
realm.delete(targetObject)
// targetObject was removed, so don't try to access it otherwise you gonna got the 'nil' value instead of object.
}
after spent a day, i figure out with the remove DispatchQueue.main.async in my realm.delete() function and finally it worked.
DispatchQueue.main.async {
realm.delete()
}
to
realm.delete()
In my case I was deleting data from 2 tables at once.. one with a foreign to the other.
let itemToDelete = counters[indexPath.row]
let realm = try! Realm()
try! realm.write {
realm.delete(itemToDelete)
let predicate = NSPredicate(format: "counterid = \(c.id)")
let children = realm.objects(Details.self).filter(predicate)
realm.delete(children)
}
But the problem was that I was trying to delete the children of the item that does not exist anymore. Switching the order, solved it!
let itemToDelete = counters[indexPath.row]
let realm = try! Realm()
try! realm.write {
let predicate = NSPredicate(format: "counterid = \(c.id)")
let children = realm.objects(Details.self).filter(predicate)
realm.delete(children)
realm.delete(itemToDelete) //this should be deleted after
}
Hope this helps someone else!
Here are some of the reasons based on my past experiences.
Overriding NSObject's isEqual(_ object: Any?), then returning identifier which was just deleted by Realm.
How did I fix it?
Check if object is invalidated if so return false otherwise proceed with using your identifier
Example:
extension YourModel {
override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? YourModel,
!self.isInvalidated else {
return false
}
return object.id == self.id
}
}
Using Diffing tools
For those using diffing tools like RxDataSources, IGListKit etc.. you have to perform the same check as mentioned above before trying to access the indentifier.
Here is a work round if you are using RxDataSources that prevent the crash caused by adopting to IdentifiableType protocol.
Check if the Realm object was invalidated. If so, just return a random unique value, like so:
var identity: String {
return isInvalidated ? "deleted-object-\(UUID().uuidString)" : objectId
}
Source: - https://github.com/RxSwiftCommunity/RxDataSources/issues/172#issuecomment-427675816
What you can do is observe the Results<> object returned from your initial Realm query (the one used to populate your list/table view) and update that list in the observer callback method whenever there is a change in the database.
Just make sure that you use the same Realm instance to delete/modify the object as the one used for the initial query.
EDIT:
Some code examples:
let realm = Realm()
let results = realm.objects(Favourite.self)
let notificationToken = results.observe { [weak self] (changes) in
guard let tableView = self?.tableView else { return }
tableView.reloadData()
}
// Somewhere else
try? realm.write {
if let favourite = results.first {
realm.delete(favourite)
}
}
// OR
if let objectRealm = results.first?.realm {
try? objectRealm.write {
objectRealm.delete(results.first!)
}
}
// Don't forget to stop observing in deinit{}
// notificationToken.invalidate()
You can also use the #ObservedRealmObject or #ObservedResults property wrapper, you implicitly open a realm and retrieve the specified objects or results. You can then pass those objects to a view further down the hierarchy.
And use the .onDelete(perform: ) method. In example: .onDelete(perform: $dogs.remove) see below:
(SwiftUI)
struct DogsView: View {
#ObservedResults(Dog.self) var dogs
/// The button to be displayed on the top left.
var leadingBarButton: AnyView?
var body: some View {
NavigationView {
VStack {
// The list shows the dogs in the realm.
// The ``#ObservedResults`` above implicitly opens a realm and retrieves
// all the Dog objects. We can then pass those objects to views further down the
// hierarchy.
List {
ForEach(dogs) { dog in
DogRow(dog: dog)
}.onDelete(perform: $dogs.remove) **//<- Deletion of the Object**
}.listStyle(GroupedListStyle())
.navigationBarTitle("Dogs", displayMode: .large)
.navigationBarBackButtonHidden(true)
.navigationBarItems(
leading: self.leadingBarButton,
// Edit button on the right to enable rearranging items
trailing: EditButton())
}.padding()
}
}
}
Souce: MongoDB - CRUD Swift SDK

iOS 8.1 with ZXING error ARC forbids explicit message send of 'autorelease'

I developed a DataMatrix Reader for Android with ZXING, and works fine, now I'm working in the version of iOS, but I have this errors when I want to use the library inside my project:
iOS SDK 8.1 and Library
ZXING: https://github.com/TheLevelUp/ZXingObjC
I use the COCOAPODS:
platform :ios, '7.0'
pod 'ZXingObjC', '~> 3.0'
I implemented the library in my project with Cocoapods, now I want to use in my App like this:
#import "ViewController.h"
#import "ZXingObjC.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)scanBarcode:(id)sender {
CGImageRef imageToDecode; // Given a CGImage in which we are looking for barcodes
ZXLuminanceSource *source = [[[ZXCGImageLuminanceSource alloc] initWithCGImage:imageToDecode] autorelease];
ZXBinaryBitmap *bitmap = [ZXBinaryBitmap binaryBitmapWithBinarizer:[ZXHybridBinarizer binarizerWithSource:source]];
NSError *error = nil;
// There are a number of hints we can give to the reader, including
// possible formats, allowed lengths, and the string encoding.
ZXDecodeHints *hints = [ZXDecodeHints hints];
ZXMultiFormatReader *reader = [ZXMultiFormatReader reader];
ZXResult *result = [reader decode:bitmap
hints:hints
error:&error];
if (result) {
// The coded result as a string. The raw data can be accessed with
// result.rawBytes and result.length.
NSString *contents = result.text;
// The barcode format, such as a QR code or UPC-A
ZXBarcodeFormat format = result.barcodeFormat;
} else {
// Use error to determine why we didn't get a result, such as a barcode
// not being found, an invalid checksum, or a format inconsistency.
}
}
#end
but I have this error:
DataMatrixReader/ViewController.m:32:99: ARC forbids explicit message
send of 'autorelease'
DataMatrixReader/ViewController.m:32:99: 'autorelease' is unavailable:
not available in automatic reference counting mode
concretly in this line:
ZXLuminanceSource *source = [[[ZXCGImageLuminanceSource alloc]
initWithCGImage:imageToDecode] autorelease];
Help from "iamnichols"...and after the change the line:
ZXLuminanceSource *source = [[[ZXCGImageLuminanceSource alloc]
initWithCGImage:imageToDecode] autorelease];
to
ZXLuminanceSource *source = [[ZXCGImageLuminanceSource alloc]
initWithCGImage:imageToDecode];
Error:
: CGBitmapContextGetData: invalid context 0x0. This is a
serious error. This application, or a library it uses, is using an
invalid context and is thereby contributing to an overall degradation
of system stability and reliability. This notice is a courtesy: please
fix this problem. It will become a fatal error in an upcoming update.
2014-12-15 12:12:36.122 DataMatrixReader[18838:412778] * Terminating
app due to uncaught exception 'NSInvalidArgumentException', reason:
'Both dimensions must be greater than 0'
* First throw call stack: ( 0 CoreFoundation 0x0000000102626f35 exceptionPreprocess + 165 1 libobjc.A.dylib
0x00000001022bfbb7 objc_exception_throw + 45 2 DataMatrixReader
0x0000000100f09507 -[ZXBitMatrix initWithWidth:height:] + 231 3
DataMatrixReader 0x0000000100f51b7d
-[ZXGlobalHistogramBinarizer blackMatrixWithError:] + 141 4 DataMatrixReader 0x0000000100f530b0
-[ZXHybridBinarizer blackMatrixWithError:] + 816 5 DataMatrixReader 0x0000000100f068ab -[ZXBinaryBitmap blackMatrixWithError:] + 139 6
DataMatrixReader 0x0000000100fa43b2
-[ZXQRCodeReader decode:hints:error:] + 130 7 DataMatrixReader 0x0000000100f63d04 -[ZXMultiFormatReader decodeInternal:error:] + 548
8 DataMatrixReader 0x0000000100f62ade
-[ZXMultiFormatReader decode:hints:error:] + 142 9 DataMatrixReader 0x0000000100ef1df2 -[ViewController scanBarcode:] + 322 10 UIKit
0x0000000102a148be -[UIApplication sendAction:to:from:forEvent:] + 75
11 UIKit 0x0000000102b1b410
-[UIControl _sendActionsForEvents:withEvent:] + 467 12 UIKit 0x0000000102b1a7df -[UIControl touchesEnded:withEvent:] + 522 13
UIKit 0x0000000102a5a308 -[UIWindow
_sendTouchesForEvent:] + 735 14 UIKit 0x0000000102a5ac33 -[UIWindow sendEvent:] + 683 15 UIKit
0x0000000102a279b1 -[UIApplication sendEvent:] + 246 16 UIKit
0x0000000102a34a7d _UIApplicationHandleEventFromQueueEvent + 17370 17
UIKit 0x0000000102a10103
_UIApplicationHandleEventQueue + 1961 18 CoreFoundation 0x000000010255c551
__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION + 17 19 CoreFoundation 0x000000010255241d
__CFRunLoopDoSources0 + 269 20 CoreFoundation 0x0000000102551a54 __CFRunLoopRun + 868 21 CoreFoundation
0x0000000102551486 CFRunLoopRunSpecific + 470 22 GraphicsServices
0x0000000104bc09f0 GSEventRunModal + 161 23 UIKit
0x0000000102a13420 UIApplicationMain + 1282 24 DataMatrixReader
0x0000000100ef2343 main + 115 25 libdyld.dylib
0x00000001058a3145 start + 1 ) libc++abi.dylib: terminating with
uncaught exception of type NSException (lldb)
Now the question is somebody tried to integrate the ZxingObjC in iOS 8.1?
I think your project is using ARC but ZXING library isn't. In that case go to path 'Target -> Build Phases -> Compile Sources' in ZXING library. Double click on each .m file and enter '-fno-objc-arc' in popped dialog box. In this way those files will be excluded from ARC
If you project is using ARC (Automatic Reference Counting) then you don't need to make autorelease calls as it is done for you.
Change
ZXLuminanceSource *source = [[[ZXCGImageLuminanceSource alloc] initWithCGImage:imageToDecode] autorelease];
to
ZXLuminanceSource *source = [[ZXCGImageLuminanceSource alloc] initWithCGImage:imageToDecode];
Further information about ARC can be found on the iOS Developer Library
This works perfectly for me:
Getting Started in the readme.md didn’t work so I had to do the following steps to make it work.
copy the whole folders into your working project’s sub-folder.
and drag/add ZXingObjC.xcodeproj file to “<your working project>”.
make sure tick create folder references for any added folders option when prompted.
then, go to your project’s Target > Build Phases
under Target Dependencies, add ZXingObjC-iOS (ZXingObjC)
under Link Binary With Libraries, add libZXingObjC-iOS.a
under the same category, add the following 6 frameworks
AVFoundation.framework
CoreGraphics.framework
CoreMedia.framework
CoreVideo.framework
ImageIO.framework
QuartzCore.framework
Source in: http://sagage.com/?p=55
My test in a direct device Iphone 4s were good, perhaps is not the best device to test that, Iphone 4s has not a "AutoFocus" feature, very important for work with this barcodes.
hope this saves your day.

Remote Connection like Browser Toolbox

I'm trying to interact with another open profile, which is a seperate process. Browser Toolbox does this. I was wondering how can I re-simulate this behavior? Without the prompt asking for "allow remote connection"?
My goal is to (1) find all open firefox process, (2) access each of its xpcom and figure out the profile name, (3) and if its a profile name Im interested in, Ill focus its most recent window.
I don't know but I'm getting somewhere by tracing it in MXR:
http://mxr.mozilla.org/mozilla-release/source/browser/devtools/framework/toolbox-process-window.js#11
11 let { debuggerSocketConnect, DebuggerClient } =
12 Cu.import("resource://gre/modules/devtools/dbg-client.jsm", {});
13 let { ViewHelpers } =
14 Cu.import("resource:///modules/devtools/ViewHelpers.jsm", {});
15
16 /**
17 * Shortcuts for accessing various debugger preferences.
18 */
19 let Prefs = new ViewHelpers.Prefs("devtools.debugger", {
20 chromeDebuggingHost: ["Char", "chrome-debugging-host"],
21 chromeDebuggingPort: ["Int", "chrome-debugging-port"]
22 });
23
24 let gToolbox, gClient;
25
26 function connect() {
27 window.removeEventListener("load", connect);
28 // Initiate the connection
29 let transport = debuggerSocketConnect(
30 Prefs.chromeDebuggingHost,
31 Prefs.chromeDebuggingPort
32 );
33 gClient = new DebuggerClient(transport);
34 gClient.connect(() => {
35 let addonID = getParameterByName("addonID");
36
37 if (addonID) {
38 gClient.listAddons(({addons}) => {
39 let addonActor = addons.filter(addon => addon.id === addonID).pop();
40 openToolbox({ addonActor: addonActor.actor, title: addonActor.name });
41 });
42 } else {
43 gClient.listTabs(openToolbox);
44 }
45 });
46 }
47
I ran the profile and it looks like the pref ..-host is localhost and ..-port is 6080. I'm not sure how this helps target a specific profile though. Maybe on start of the browser toolbox it opened port 6080 to the opener profile. I'm not sure, but if its true, then you'll have to run code from within the target profile to open a port maybe.
Totally not sure though.
But port is opened here:
http://mxr.mozilla.org/mozilla-release/source/browser/devtools/framework/ToolboxProcess.jsm#107
106
107 BrowserToolboxProcess.prototype = {
108 /**
109 * Initializes the debugger server.
110 */
111 _initServer: function() {
112 dumpn("Initializing the chrome toolbox server.");
113
114 if (!this.loader) {
115 // Create a separate loader instance, so that we can be sure to receive a
116 // separate instance of the DebuggingServer from the rest of the devtools.
117 // This allows us to safely use the tools against even the actors and
118 // DebuggingServer itself, especially since we can mark this loader as
119 // invisible to the debugger (unlike the usual loader settings).
120 this.loader = new DevToolsLoader();
121 this.loader.invisibleToDebugger = true;
122 this.loader.main("devtools/server/main");
123 this.debuggerServer = this.loader.DebuggerServer;
124 dumpn("Created a separate loader instance for the DebuggerServer.");
125
126 // Forward interesting events.
127 this.debuggerServer.on("connectionchange", this.emit.bind(this));
128 }
129
130 if (!this.debuggerServer.initialized) {
131 this.debuggerServer.init();
132 this.debuggerServer.addBrowserActors();
133 dumpn("initialized and added the browser actors for the DebuggerServer.");
134 }
135
136 this.debuggerServer.openListener(Prefs.chromeDebuggingPort);
137
138 dumpn("Finished initializing the chrome toolbox server.");
139 dumpn("Started listening on port: " + Prefs.chromeDebuggingPort);
140 },
141

Resources