Updating Old Realm Objects From 2016 Causes Crash - xcode

Help! I'm updating an old Xcode project from 2016 and I'm encountering crashes when working with my Realm objects.
I have a game I built in Xcode with swift 3 and put in the AppStore in 2016. It used Realm for my Game objects. It was one of my first projects so recently I decided to revisit the project and update the code, clean it up (I was very new to Swift), make it work with newer devices and screens, fix a couple bugs, add a few features, etc. When going through the updates to the current languages, I can no longer save my Game object because in 2016, the Realm properties were written as:
dynamic var numCorrect: Int = 0
dynamic var numWrong: Int = 0
dynamic var score: Int = 0
dynamic var stars: Int = 0
dynamic var date = NSDate()
...
Now Realm requires "#objc" before "dynamic var". So it's now:
#objc dynamic var numCorrect: Int = 0
#objc dynamic var numWrong: Int = 0
#objc dynamic var score: Int = 0
#objc dynamic var stars: Int = 0
#objc dynamic var date = NSDate()
With this change/addition everything works great. UNTIL I try to update on top of the old/current version in the App Store. It crashes when trying to create a new Game object.
I assume there's some way to migrate but I can't figure it out. The migration guide doesn't address upgrading from an old version of Realm to a new version.
Here's the log:
/Users/realm/workspace/realm_realm-core_release_6.0.6/src/realm/group.hpp:1149: [realm-core-6.0.6] Assertion failed: m_top.size() > s_hist_version_ndx
0 Realm 0x0000000103b5db04 _ZN5realm4utilL18terminate_internalERNSt3__118basic_stringstreamIcNS1_11char_traitsIcEENS1_9allocatorIcEEEE + 28
1 Realm 0x0000000103b5dda0 _ZN5realm4util9terminateEPKcS2_lOSt16initializer_listINS0_9PrintableEE + 324
2 Realm 0x0000000103a97720 _ZN5realm2DB19upgrade_file_formatEbiii + 980
3 Realm 0x0000000103a95130 _ZN5realm2DB7do_openERKNSt3__112basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEEbbNS_9DBOptionsE + 3092
4 Realm 0x0000000103a97b20 _ZN5realm2DB4openERNS_11ReplicationENS_9DBOptionsE + 244
5 Realm 0x0000000103a9c0a4 _ZN5realm2DB6createERNS_11ReplicationENS_9DBOptionsE + 392
6 Realm 0x0000000103644a44 _ZN5realm5_impl16RealmCoordinator7open_dbEv + 972
7 Realm 0x0000000103643c98 _ZN5realm5_impl16RealmCoordinator12do_get_realmENS_5Realm6ConfigERNSt3__110shared_ptrIS2_EENS_4util8OptionalINS_9VersionIDEEERNS8_17CheckedUniqueLockE + 72
8 Realm 0x0000000103643b30 _ZN5realm5_impl16RealmCoordinator9get_realmENS_5Realm6ConfigENS_4util8OptionalINS_9VersionIDEEE + 268
9 Realm 0x0000000103895ae0 _ZN5realm5Realm16get_shared_realmENS0_6ConfigE + 152
10 Realm 0x00000001037e0434 +[RLMRealm realmWithConfiguration:queue:error:] + 1704
11 RealmSwift 0x0000000104be1660 $sSo8RLMRealmC13configuration5queueABSo0A13ConfigurationC_So012OS_dispatch_C0CSgtKcfCTO + 156
12 RealmSwift 0x0000000104c18aa8 $s10RealmSwift0A0V5queueACSo012OS_dispatch_C0CSg_tKcfC + 140
13 Scrath 0x00000001028afa4c $s6Scrath11AppDelegateC11updateRealmyyF + 680
14 Scrath 0x00000001028af438 $s6Scrath11AppDelegateC11application_29didFinishLaunchingWithOptionsSbSo13UIApplicationC_SDySo0j6LaunchI3KeyaypGSgtF + 288
15 Scrath 0x00000001028af534 $s6Scrath11AppDelegateC11application_29didFinishLaunchingWithOptionsSbSo13UIApplicationC_SDySo0j6LaunchI3KeyaypGSgtFTo + 232
16 UIKitCore 0x00000001c31e478c 66C0BDEB-71CF-3148-AF27-A5B055FAD9A5 + 10893196
17 UIKitCore 0x00000001c31e656c 66C0BDEB-71CF-3148-AF27-A5B055FAD9A5 + 10900844
18 UIKitCore 0x00000001c31ebf68 66C0BDEB-71CF-3148-AF27-A5B055FAD9A5 + 10923880
19 UIKitCore 0x00000001c295eb50 66C0BDEB-71CF-3148-AF27-A5B055FAD9A5 + 1956688
20 UIKitCore 0x00000001c2e29510 _UIScenePerformActionsWithLifecycleActionMask + 112
21 UIKitCore 0x00000001c295f684 66C0BDEB-71CF-3148-AF27-A5B055FAD9A5 + 1959556
22 UIKitCore 0x00000001c295f0b0 66C0BDEB-71CF-3148-AF27-A5B055FAD9A5 + 1958064
23 UIKitCore 0x00000001c295f4a0 66C0BDEB-71CF-3148-AF27-A5B055FAD9A5 + 1959072
24 UIKitCore 0x00000001c295ed28 66C0BDEB-71CF-3148-AF27-A5B055FAD9A5 + 1957160
25 UIKitCore 0x00000001c2963444 66C0BDEB-71CF-3148-AF27-A5B055FAD9A5 + 1975364
26 UIKitCore 0x00000001c2d48080 66C0BDEB-71CF-3148-AF27-A5B055FAD9A5 + 6058112
27 UIKitCore 0x00000001c2e431b4 _UISceneSettingsDiffActionPerformChangesWithTransitionContext + 260
28 UIKitCore 0x00000001c2963180 66C0BDEB-71CF-3148-AF27-A5B055FAD9A5 + 1974656
29 UIKitCore 0x00000001c2e4309c _UISceneSettingsDiffActionPerformActionsWithDelayForTransitionContext + 108
30 UIKitCore 0x00000001c2962fd8 66C0BDEB-71CF-3148-AF27-A5B055FAD9A5 + 1974232
31 UIKitCore 0x00000001c27c8db8 66C0BDEB-71CF-3148-AF27-A5B055FAD9A5 + 294328
32 UIKitCore 0x00000001c27c78b8 66C0BDEB-71CF-3148-AF27-A5B055FAD9A5 + 288952
33 UIKitCore 0x00000001c27c8ae8 66C0BDEB-71CF-3148-AF27-A5B055FAD9A5 + 293608
34 UIKitCore 0x00000001c31ea200 66C0BDEB-71CF-3148-AF27-A5B055FAD9A5 + 10916352
35 UIKitCore 0x00000001c2d6ea50 66C0BDEB-71CF-3148-AF27-A5B055FAD9A5 + 6216272
36 FrontBoardServices 0x00000001c4304bec 039FCB83-A7EC-3872-94E8-DD490434EAEB + 52204
37 FrontBoardServices 0x00000001c432b190 039FCB83-A7EC-3872-94E8-DD490434EAEB + 209296
38 FrontBoardServices 0x00000001c430faac 039FCB83-A7EC-3872-94E8-DD490434EAEB + 96940
39 FrontBoardServices 0x00000001c432ae24 039FCB83-A7EC-3872-94E8-DD490434EAEB + 208420
40 libdispatch.dylib 0x0000000104da318c _dispatch_client_callout + 20
41 libdispatch.dylib 0x0000000104da6964 _dispatch_block_invoke_direct + 368
42 FrontBoardServices 0x00000001c43512b4 039FCB83-A7EC-3872-94E8-DD490434EAEB + 365236
43 FrontBoardServices 0x00000001c4350f60 039FCB83-A7EC-3872-94E8-DD490434EAEB + 364384
44 FrontBoardServices 0x00000001c43514cc 039FCB83-A7EC-3872-94E8-DD490434EAEB + 365772
45 CoreFoundation 0x00000001bf01f860 9624AAFD-5437-3772-A507-0F357875808D + 710752
46 CoreFoundation 0x00000001bf01f7b4 9624AAFD-5437-3772-A507-0F357875808D + 710580
47 CoreFoundation 0x00000001bf01ef04 9624AAFD-5437-3772-A507-0F357875808D + 708356
48 CoreFoundation 0x00000001bf019ca4 9624AAFD-5437-3772-A507-0F357875808D + 687268
49 CoreFoundation 0x00000001bf019660 CFRunLoopRunSpecific + 480
50 GraphicsServices 0x00000001c942a604 GSEventRunModal + 164
51 UIKitCore 0x00000001c31ee15c UIApplicationMain + 1944
52 Scrath 0x00000001028b16a4 main + 80
53 libdyld.dylib 0x00000001bee951ec 95B366E7-F5BD-3308-9416-24B35999029B + 4588!!! IMPORTANT: Please send this log and info about Realm SDK version and other relevant reproduction info to help#realm.io
Please, does anyone know how to solve this? It's not like this app is popular but I don't want to require any previous user to delete the app in order to use the new version.

I would try to implement a migration block and use enumerate as follows:
migration.enumerateObjects(ofType: Object.className()) { (oldObject, newObject) in
guard let numCorrect = oldObject?["numCorrect"] as? Int else {
fatalError("numCorrect is not a Int")
}
// List all the rest of your properties the same way (i.e., with a guard statement)
// Then assign old object value to new property
newObject?["numCorrect"] = numCorrect
}
Make sure you implement your migration block properly with the right version etc..

For anyone having this problem, it appears to be a bug with Realm's current version. In my podfile I wrote:
pod 'RealmSwift', '<5.0'
pod 'Realm', '<5.0'
And now my project runs perfectly. Thanks #RobertCrabtree!

Related

Xamarin Forms (iOS): This application is modifying the autolayout engine

Since I added translations between two ContentViews (to go from one to the other one nicely), I have the following logs:
This application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread. This can lead to engine corruption and weird crashes.
Stack:(
0 Foundation 0x0000000110da2ec6 _AssertAutolayoutOnAllowedThreadsOnly + 77
1 Foundation 0x0000000110da2b89 -[NSISEngine _optimizeWithoutRebuilding] + 61
2 Foundation 0x0000000110bb1ebb -[NSISEngine optimize] + 108
3 Foundation 0x0000000110da00ac -[NSISEngine performPendingChangeNotifications] + 84
4 UIKit 0x00000001116f89f9 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 2211
5 QuartzCore 0x00000001138a63ee -[CALayer layoutSublayers] + 153
6 QuartzCore 0x00000001138aa4dd _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 401
7 QuartzCore 0x0000000113832ded _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 365
8 QuartzCore 0x000000011385e704 _ZN2CA11Transaction6commitEv + 500
9 MyProject.iOS 0x000000010f6bbd39 xamarin_dyn_objc_msgSend + 217
10 ??? 0x000000012f8e9462 0x0 + 5092840546
11 ??? 0x000000013025827c 0x0 + 5102731900
12 MyProject.iOS 0x000000010f5272c9 mono_jit_runtime_invoke + 1273
13 MyProject.iOS 0x000000010f5dbaa8 do_runtime_invoke + 88
14 MyProject.iOS 0x000000010f61bf9e start_wrapper + 718
15 libsystem_pthread.dylib 0x0000000117fe06c1 _pthread_body + 340
16 libsystem_pthread.dylib 0x0000000117fe056d _pthread_body + 0
17 libsystem_pthread.dylib 0x0000000117fdfc5d thread_start + 13
)
This is my code:
Device.BeginInvokeOnMainThread(async () =>
{
DetailContentView.Children.Insert(0, masterDetailContentView);
await DetailContentView.Children[1].TranslateTo(App.ScreenWidth - 100, 0, 250);
await DetailContentView.Children[1].TranslateTo(App.ScreenWidth, 0, 50);
DetailContentView.Children.RemoveAt(1);
});
where DetailContentView is a Grid, masterDetailContentView is the ContentView that will appear and DetailContentView.Children[1] is the ContentView that will disappear.
This piece of code works but I want to remove the logs.
Thanks!

How do I restore indexing functionality? (Xcode)

One of my projects (containing over 200 files in pure Swift) has just recently started interfering with the indexing process. The indexing process freezes midway and then stops abruptly, causing SourceKitService to crash.
I simply cannot find the faulty code; because there appears to be none!
My code compiles just fine (without a single warning!) - and yet it fails to be indexed. Initially, I thought it to be an Xcode 7.2 issue and so upgraded to the latest beta (7.3); however the issue still persists. I cannot revert back to my old code because too much work will be undone, and I can't spot a particular file to blame. The crash report is here.
To clarify, Xcode itself does not crash, only the indexing process (and SourceKitService as a consequence).
Any ideas on how to go about fixing this?
Remove "xcuserdata" from .xcodeproj (right click on .xcodeproj > select Show Package Contents. This should solve the problem.
If I'm reading properly,
the problem comes from this part of the process:
Thread 8 Crashed:
0 com.apple.SourceKitService 0x000000010450d9fc swift::TypeBase::getDesugaredType() + 12
1 com.apple.SourceKitService 0x00000001043bccbe (anonymous namespace)::DeclChecker::checkDynamicSelfReturn(swift::FuncDecl*, swift::TypeRepr*, unsigned int) + 478
2 com.apple.SourceKitService 0x00000001043b7c08 (anonymous namespace)::DeclChecker::visitFuncDecl(swift::FuncDecl*) + 1432
3 com.apple.SourceKitService 0x00000001043acc0d (anonymous namespace)::DeclChecker::visit(swift::Decl*) + 2733
4 com.apple.SourceKitService 0x00000001043a7ea7 swift::TypeChecker::validateDecl(swift::ValueDecl*, bool) + 727
5 com.apple.SourceKitService 0x00000001043b6426 (anonymous namespace)::DeclChecker::visitSubscriptDecl(swift::SubscriptDecl*) + 1478
6 com.apple.SourceKitService 0x00000001043acbdd (anonymous namespace)::DeclChecker::visit(swift::Decl*) + 2685
7 com.apple.SourceKitService 0x00000001043a7ea7 swift::TypeChecker::validateDecl(swift::ValueDecl*, bool) + 727
8 com.apple.SourceKitService 0x00000001044fc003 swift::DeclContext::lookupQualified(swift::Type, swift::DeclName, unsigned int, swift::LazyResolver*, llvm::SmallVectorImpl<swift::ValueDecl*>&) const + 3075
9 com.apple.SourceKitService 0x00000001043c7a7c swift::TypeChecker::lookupMember(swift::DeclContext*, swift::Type, swift::DeclName, swift::OptionSet<swift::NameLookupFlags, unsigned int>) + 556
10 com.apple.SourceKitService 0x00000001043d51b7 (anonymous namespace)::ConformanceChecker::lookupValueWitnesses(swift::ValueDecl*, bool*) + 359
11 com.apple.SourceKitService 0x00000001043d11a1 (anonymous namespace)::ConformanceChecker::resolveWitnessViaLookup(swift::ValueDecl*) + 401
12 com.apple.SourceKitService 0x00000001043ce86f swift::TypeChecker::checkConformance(swift::NormalProtocolConformance*) + 2255
13 com.apple.SourceKitService 0x000000010438011b typeCheckFunctionsAndExternalDecls(swift::TypeChecker&) + 1099
14 com.apple.SourceKitService 0x00000001043809e5 swift::performTypeChecking(swift::SourceFile&, swift::TopLevelContext&, swift::OptionSet<swift::TypeCheckingFlags, unsigned int>, unsigned int) + 1781
15 com.apple.SourceKitService 0x0000000103fa40c2 swift::CompilerInstance::performSema() + 4738
16 com.apple.SourceKitService 0x0000000103e9a836 SourceKit::SwiftLangSupport::indexSource(llvm::StringRef, SourceKit::IndexingConsumer&, llvm::ArrayRef<char const*>, llvm::StringRef) + 4262
17 com.apple.SourceKitService 0x0000000103eb086a void SourceKit::WorkQueue::DispatchData::callAndDelete<handleRequestImpl(void*, std::__1::function<void (void*)>)::$_2>(void*) + 2170
18 libdispatch.dylib 0x00007fff9b7de33f _dispatch_client_callout + 8
19 libdispatch.dylib 0x00007fff9b7ec03a _dispatch_block_invoke + 474
20 com.apple.SourceKitService 0x00000001056afbbf executeBlock(void*) + 15
21 com.apple.SourceKitService 0x0000000103f3e58d ExecuteOnThread_Dispatch(void*) + 13
22 libsystem_pthread.dylib 0x00007fff8be14c13 _pthread_body + 131
23 libsystem_pthread.dylib 0x00007fff8be14b90 _pthread_start + 168
24 libsystem_pthread.dylib 0x00007fff8be12375 thread_start + 13
which leads us to :
https://github.com/apple/swift/pull/932/files
20days + ago
So I guess it's a known issue.
However I don't know what is causing it. I'm pretty sure it's a swift code style that is not well supported yet.
I also found your crash in this Crash test project:
https://github.com/practicalswift/swift-compiler-crashes
If you look into it, you might find the precise case that triggers one of those crashes:
✓ 28197 swift typebase getdesugaredtype
✓ 28200 swift typebase getdesugaredtype
✓ 28203 swift typebase getdesugaredtype

Got "valueForUndefinedKey: this class is not key value coding-compliant for the key error" when use NSArrayController

I'm working for NSCollectionView by using Swift. When I use a NSArrayController object as content of NSCollectionView. I got follow error:
An uncaught exception was raised
[ valueForUndefinedKey:]: this class is not key value coding-compliant for the key plugName .
I have no idea why. I create a model named NHPlug and a NSArrayController as follow, here's my code. :
/* Class NHAppController */
import Cocoa
class NHAppController: NSObject {
#IBOutlet weak var arrayController: NSArrayController?
var plugs: NSMutableArray?
override func awakeFromNib() {
var t = NHPlug(plugID: 1, plugName: "test")
plugs = NSMutableArray()
arrayController?.addObject(t)
}
}
/* Class NSPlug */
import Cocoa
class NHPlug: NSObject {
var plugID : Int
var plugName : String
init(plugID: Int, plugName: String) {
self.plugID = plugID
self.plugName = plugName;
}
}
If anybody could help, very appreciate for that!
And here if crash stack:
-01-21 19:47:07.347 Notifyhub[58369:598950] An uncaught exception was raised 2015-01-21 19:47:07.347 Notifyhub[58369:598950]
[ valueForUndefinedKey:]: this class
is not key value coding-compliant for the key plugName . 2015-01-21
19:47:07.348 Notifyhub[58369:598950] ( 0 CoreFoundation
0x00007fff9220b64c __exceptionPreprocess + 172 1 libobjc.A.dylib
0x00007fff950966de objc_exception_throw + 43 2 CoreFoundation
0x00007fff9220b1e9 -[NSException raise] + 9 3 Foundation
0x00007fff8bd6c5ed -[NSObject(NSKeyValueCoding) valueForUndefinedKey:]
+ 226 4 Foundation 0x00007fff8bc89e68 -[NSObject(NSKeyValueCoding) valueForKey:] + 385 5 Foundation 0x00007fff8bca28e3 -[NSObject(NSKeyValueCoding) valueForKeyPath:] +
324 6 Foundation 0x00007fff8bca28af
-[NSObject(NSKeyValueCoding) valueForKeyPath:] + 272 7 AppKit 0x00007fff8975c8bf -[NSBinder
valueForBinding:resolveMarkersToPlaceholders:] + 164 8 AppKit
0x00007fff89760700 -[NSValueBinder
_adjustObject:mode:observedController:observedKeyPath:context:editableState:adjustState:]
+ 302 9 AppKit 0x00007fff8976053b -[NSValueBinder _observeValueForKeyPath:ofObject:context:] + 276 10 AppKit 0x00007fff897603ab
-[NSTextValueBinder _observeValueForKeyPath:ofObject:context:] + 43 11 Foundation 0x00007fff8bc63c73
NSKeyValueNotifyObserver + 382 12 Foundation
0x00007fff8bc62e48 NSKeyValueDidChange + 463 13 Foundation
0x00007fff8bc679ad -[NSObject(NSKeyValueObserverNotification)
didChangeValueForKey:] + 118 14 AppKit
0x00007fff89eb5e83 -[NSCollectionView newItemForRepresentedObject:] +
87 15 AppKit 0x00007fff89ebce03
-[NSCollectionView _getItemsToDisplay] + 1168 16 AppKit 0x00007fff89eb5595 -[NSCollectionView setContent:] + 217 17 AppKit
0x00007fff89e8e965 -[NSCollectionViewBinder _updateContent] + 93 18
AppKit 0x00007fff89e8e9f0
-[NSCollectionViewBinder _observeValueForKeyPath:ofObject:context:] + 84 19 Foundation 0x00007fff8bc63c73
NSKeyValueNotifyObserver + 382 20 Foundation
0x00007fff8bca22a6 -[NSObject(NSKeyValueObservingPrivate)
_notifyObserversForKeyPath:change:] + 1142 21 AppKit 0x00007fff897533ba -[NSController _notifyObserversForKeyPath:change:]
+ 206 22 AppKit 0x00007fff8984f126 -[NSArrayController didChangeValuesForArrangedKeys:objectKeys:indexKeys:] + 54 23 AppKit
0x00007fff89a1dbd0 -[NSArrayController
_insertObject:atArrangedObjectIndex:objectHandler:] + 514 24 AppKit 0x00007fff89a1d82c -[NSArrayController addObject:] + 153 25
Notifyhub 0x000000010000166a
_TFC9Notifyhub15NHAppController12awakeFromNibfS0_FT_T_ + 362 26 Notifyhub 0x00000001000016d2
_TToFC9Notifyhub15NHAppController12awakeFromNibfS0_FT_T_ + 34 27 CoreFoundation 0x00007fff9211983f -[NSSet
makeObjectsPerformSelector:] + 223 28 AppKit
0x00007fff89ba2ffd -[NSIBObjectData
nibInstantiateWithOwner:options:topLevelObjects:] + 1216 29 AppKit
0x00007fff89c22122 -[NSNib
_instantiateNibWithExternalNameTable:options:] + 677 30 AppKit 0x00007fff89c22236 -[NSNib
_instantiateWithOwner:options:topLevelObjects:] + 143 31 AppKit 0x00007fff89d5f36c -[NSStoryboard
instantiateControllerWithIdentifier:] + 181 32 AppKit
0x00007fff896afef4 NSApplicationMain + 840 33 Notifyhub
0x00000001000011c2 top_level_code + 34 34 Notifyhub
0x00000001000011fa main + 42 35 libdyld.dyli
Got the answer myself. Post here to help any poor new guy for Swift.
In Swift KVO is not default support any more, when you declare a variable must set "dynamic" as follow:
dynamic var plugID : Int
dynamic var plugName : String

Adding text container to NSLayoutManager results in exception

In my cocoa application (written in Swift), I am trying to make a pagination system, where each page is an instance of CASTextView (a subclass of NSTextView). Additionally, each CASTextView retains an instance of CASTextContainer (a subclass of NSTextContainer). In order to accomplish pagination, I have made all instances of CASTextView share the same NSLayoutManager instance via a singleton pattern.
I have implemented the method - (void)layoutManager:(NSLayoutManager *)aLayoutManager didCompleteLayoutForTextContainer:(NSTextContainer *)aTextContainer atEnd:(BOOL)flag as follows:
func layoutManager(layoutManager: NSLayoutManager!,
didCompleteLayoutForTextContainer textContainer: NSTextContainer!,
atEnd layoutFinishedFlag: Bool)
{
let containers = layoutManager.textContainers
if !layoutFinishedFlag || !textContainer {
let lastContainer = containers[containers.count - 1] as NSTextContainer
if !textContainer || textContainer == lastContainer {
if layoutManager.glyphRangeForTextContainer(lastContainer).length > 0 {
addPage(nil)
}
}
}
}
Here is the code to receive the singleton instance of NSLayoutManager (CASTextView.sharedLayoutManager):
class var sharedLayoutManager: NSLayoutManager {
struct Singleton {
static let instance = NSLayoutManager()
}
return Singleton.instance // All text containers share the same layout manager.
}
The method addPage initializes a text view, replaces the text container with one of type CASTextContainer, and then replaces the layout manager with the shared layout manager, as follows:
func addPage(sender: NSNotification?) {
let midpoint = NSWidth(mainView.frame) / 2
let firstEndpoint = midpoint - 500
var rect: NSRect = NSZeroRect
let yValue: CGFloat = 50 + 1425 * CGFloat(pages.count)
mainView.frame.size = NSMakeSize(NSWidth(mainView.frame), yValue + 1675) // extend the scrolling size to account for new subview.
let origin = NSMakePoint(firstEndpoint, yValue)
let size = NSMakeSize(1000, 1375)
rect.origin = origin
rect.size = size
var nextView = CASTextView(frame: rect)
var nextContainer = CASTextContainer(containerSize: containerSize)
nextContainer.mainView = nextView
nextView.replaceTextContainer(nextContainer)
nextContainer.replaceLayoutManager(CASTextView.sharedLayoutManager)
nextView.autoresizingMask = NSAutoresizingMaskOptions.ViewNotSizable
nextView.delegate = nextView
nextView.usesFindPanel = true
mainView.addSubview(nextView)
pages.append(nextView)
for var i = 0; i < pages.count - 1; ++i {
pages[i].nextPage = pages[i + 1] // reset nextPage variable
}
}
Each CASTextView retains a reference to the next page (also of type CASTextView), and the last CASTextView is to have this reference (called nextPage) set to nil. The variable 'pages' is an array of all of the pages retained by the NSLayoutManagerDelegate (a subclass of NSViewController).
The problem: The call to addPage is executing exactly when it is intended to (when one page's text container can no longer fit all of the text), but is causing an exception to occur in the following method:
-[NSBigMutableString _getBlockStart:end:contentsEnd:forRange:stopAtLineSeparators:]: Range {0, 98} out of bounds; string length 0
I cannot find documentation on this method anywhere; the leading underscore seems to imply that it is a private method of NSString, but the stack trace shows that it is being called by -[NSString paragraphRangeForRange:] . Interestingly, the stack trace does not show that the addPage method is on the stack. Here is the stack trace:
0 CoreFoundation 0x00007fff90ef3f1c __exceptionPreprocess + 172
1 libobjc.A.dylib 0x00007fff869b274e objc_exception_throw + 43
2 CoreFoundation 0x00007fff90ef3dcd +[NSException raise:format:] + 205
3 Foundation 0x00007fff8d480b5c -[NSString _getBlockStart:end:contentsEnd:forRange:stopAtLineSeparators:] + 239
4 Foundation 0x00007fff8d4a699c -[NSString paragraphRangeForRange:] + 57
5 AppKit 0x00007fff8ea8a7fe -[NSTextView _markTextEditedForRange:] + 1405
6 AppKit 0x00007fff8ea852a0 -[NSTextView insertText:replacementRange:] + 2800
7 AppKit 0x00007fff8eaba451 -[NSTextView insertText:] + 318
8 AppKit 0x00007fff8eade292 -[NSTextView(NSKeyBindingCommands) insertNewline:] + 239
9 AppKit 0x00007fff8ea8f544 -[NSTextView doCommandBySelector:] + 195
10 AppKit 0x00007fff8f0b6a71 -[NSTextInputContext(NSInputContext_WithCompletion) doCommandBySelector:completionHandler:] + 118
11 AppKit 0x00007fff8ea64c9b -[NSKeyBindingManager(NSKeyBindingManager_MultiClients) interpretEventAsCommand:forClient:] + 1899
12 AppKit 0x00007fff8f0b54a2 __61-[NSTextInputContext _handleEvent:options:completionHandler:]_block_invoke968 + 335
13 AppKit 0x00007fff8f0b6edf -[NSTextInputContext(NSInputContext_WithCompletion) hasMarkedTextWithCompletionHandler:] + 76
14 AppKit 0x00007fff8f0b52c3 __61-[NSTextInputContext _handleEvent:options:completionHandler:]_block_invoke_3 + 95
15 AppKit 0x00007fff8f0b45d8 -[NSTextInputContext tryHandleEvent_HasMarkedText_withDispatchCondition:dispatchWork:continuation:] + 101
16 AppKit 0x00007fff8f0b5234 __61-[NSTextInputContext _handleEvent:options:completionHandler:]_block_invoke956 + 321
17 HIToolbox 0x00007fff8e0e204f __TSMProcessRawKeyEventWithOptionsAndCompletionHandler_block_invoke_5 + 70
18 AppKit 0x00007fff8f0ae056 __55-[NSTextInputContext handleTSMEvent:completionHandler:]_block_invoke174 + 2387
19 AppKit 0x00007fff8f0b6edf -[NSTextInputContext(NSInputContext_WithCompletion) hasMarkedTextWithCompletionHandler:] + 76
20 AppKit 0x00007fff8f0ad674 __55-[NSTextInputContext handleTSMEvent:completionHandler:]_block_invoke_2 + 95
21 AppKit 0x00007fff8f0ab3c8 -[NSTextInputContext tryHandleTSMEvent_HasMarkedText_withDispatchCondition:dispatchWork:continuation:] + 101
22 AppKit 0x00007fff8f0ad3d0 -[NSTextInputContext handleTSMEvent:completionHandler:] + 3293
23 AppKit 0x00007fff8ea8410e _NSTSMEventHandler + 324
24 HIToolbox 0x00007fff8decd6c8 _ZL23DispatchEventToHandlersP14EventTargetRecP14OpaqueEventRefP14HandlerCallRec + 1128
25 HIToolbox 0x00007fff8deccb8e _ZL30SendEventToEventTargetInternalP14OpaqueEventRefP20OpaqueEventTargetRefP14HandlerCallRec + 386
26 HIToolbox 0x00007fff8decca02 SendEventToEventTargetWithOptions + 43
27 HIToolbox 0x00007fff8e0db37c SendTSMEvent_WithCompletionHandler + 417
28 HIToolbox 0x00007fff8e0db87c __SendUnicodeTextAEToUnicodeDoc_WithCompletionHandler_block_invoke + 400
29 HIToolbox 0x00007fff8e0dbb36 __SendFilterTextEvent_WithCompletionHandler_block_invoke + 189
30 HIToolbox 0x00007fff8e0db3d0 SendTSMEvent_WithCompletionHandler + 501
31 HIToolbox 0x00007fff8e0db6bf SendFilterTextEvent_WithCompletionHandler + 236
32 HIToolbox 0x00007fff8e0d8a31 SendUnicodeTextAEToUnicodeDoc_WithCompletionHandler + 295
33 HIToolbox 0x00007fff8e0dd329 __utDeliverTSMEvent_WithCompletionHandler_block_invoke_2 + 296
34 HIToolbox 0x00007fff8e0dd1f8 __utDeliverTSMEvent_WithCompletionHandler_block_invoke + 437
35 HIToolbox 0x00007fff8e0d84ad TSMKeyEvent_WithCompletionHandler + 701
36 HIToolbox 0x00007fff8e0e1fd0 __TSMProcessRawKeyEventWithOptionsAndCompletionHandler_block_invoke_4 + 251
37 HIToolbox 0x00007fff8e0e1ec6 __TSMProcessRawKeyEventWithOptionsAndCompletionHandler_block_invoke_3 + 330
38 HIToolbox 0x00007fff8e0e1d02 __TSMProcessRawKeyEventWithOptionsAndCompletionHandler_block_invoke_2 + 259
39 HIToolbox 0x00007fff8e0e1b85 __TSMProcessRawKeyEventWithOptionsAndCompletionHandler_block_invoke + 251
40 HIToolbox 0x00007fff8e0e198f TSMProcessRawKeyEventWithOptionsAndCompletionHandler + 3068
41 AppKit 0x00007fff8f0b5046 __61-[NSTextInputContext _handleEvent:options:completionHandler:]_block_invoke945 + 131
42 AppKit 0x00007fff8f0b4502 -[NSTextInputContext tryTSMProcessRawKeyEvent:dispatchCondition:setupForDispatch:furtherCondition:dispatchWork:continuation:] + 127
43 AppKit 0x00007fff8f0b4b35 -[NSTextInputContext _handleEvent:options:completionHandler:] + 1266
44 AppKit 0x00007fff8ea8394e -[NSTextInputContext handleEvent:] + 109
45 AppKit 0x00007fff8ea63368 -[NSView interpretKeyEvents:] + 207
46 AppKit 0x00007fff8ea837cd -[NSTextView keyDown:] + 695
47 AppKit 0x00007fff8efa2d7b -[NSWindow _reallySendEvent:] + 1959
48 AppKit 0x00007fff8ea337bc -[NSWindow sendEvent:] + 368
49 AppKit 0x00007fff8e9e5dc0 -[NSApplication sendEvent:] + 4008
50 AppKit 0x00007fff8e871b48 -[NSApplication run] + 711
51 AppKit 0x00007fff8e85d2de NSApplicationMain + 1778
52 Application 0x000000010000e2a5 top_level_code + 37
53 Application 0x000000010000e2da main + 42
54 libdyld.dylib 0x00007fff9422d5c9 start + 1
55 ??? 0x0000000000000003 0x0 + 3
)
The error was occurring as a result of my call to replaceLayoutManager. I altered the way that I initialize the text view. Rather than using the init(frame: frameRect) constructor, I utilized the designated initializer by separately initializing a text container as such:
var nextContainer = CASTextContainer(containerSize: containerSize)
var nextView = CASTextView(frame: rect, textContainer: nextContainer)
I then proceeded to call mainView.addSubview(nextView), and after the subview was added, I called the following:
CASTextView.sharedLayoutManager.addTextContainer(nextContainer)
which then allowed for the pagination effect to take place.

NSWindow base() constructor crashing with NSInternalInconsistencyException on Monodevelop

I am trying to run on Monodevelop (latest Git) a solution that runs fine on Xamarin.Mac
It crashes at the base() line:
public class SetupWindow : NSWindow {
public List <NSButton> Buttons = new List <NSButton> ();
public string Header;
public string Description;
private NSImage side_splash;
private NSImageView side_splash_view;
private NSTextField header_text_field;
private NSTextField description_text_field;
public SetupWindow () : base ()
{
SetFrame (new RectangleF (0, 0, 640, 420), true);
With this output:
2014-02-06 18:05:28.567 mono[8564:507] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Error (1000) creating CGSWindow on line 263'
*** Call stack at first throw:
(
0 CoreFoundation 0x927956b1 __raiseError + 193
1 libobjc.A.dylib 0x96f38091 objc_exception_throw + 162
2 CoreFoundation 0x927955cb +[NSException raise:format:] + 139
3 AppKit 0x97f434b3 _NSCreateWindowWithOpaqueShape2 + 1718
4 AppKit 0x97f41f3a -[NSWindow _commonAwake] + 4391
5 AppKit 0x97e167fb -[NSWindow _commonInitFrame:styleMask:backing:defer:] + 864
6 AppKit 0x97e15de3 -[NSWindow _initContent:styleMask:backing:defer:contentView:] + 1090
7 AppKit 0x97e1599a -[NSWindow initWithContentRect:styleMask:backing:defer:] + 70
8 AppKit 0x9860919a -[NSWindow init] + 107
9 ??? 0x02a01d22 0x0 + 44047650
10 ??? 0x04095ebc 0x0 + 67722940
11 ??? 0x04095108 0x0 + 67719432
12 ??? 0x02a02c34 0x0 + 44051508
13 ??? 0x029fec8c 0x0 + 44035212
14 ??? 0x02296b84 0x0 + 36268932
15 ??? 0x02296e9f 0x0 + 36269727
16 mono 0x0007b2ee mono_jit_runtime_invoke + 798
17 mono 0x0023500e mono_runtime_invoke + 126
18 mono 0x002395c4 mono_runtime_exec_main + 420
19 mono 0x00239935 mono_runtime_run_main + 725
20 mono 0x000e68d5 mono_jit_exec + 149
21 mono 0x000e8f12 mono_main + 9778
22 mono 0x0006e9fe main + 558
23 mono 0x0006e7c5 start + 53
Any idea what is going wrong?
Because of another problem, I commented out the lines that set images for NSApplication.SharedApplication.ApplicationIconImage and NSWorkspace.SharedWorkspace.SetIconforFile, could that be the problem?
A colleague tried on his brand new Mac, and gets the exact same problem.
The problem was fixed by adding these two lines before instantiating SetupWindow:
NSApplication.SharedApplication.ApplicationIconImage = image;
SetFolderIcon ();
Now the application runs fine.

Resources