Air Printing crash on ipad - ipad

I am having a trouble with printing on ipad. My code prints the pdf file perfectly for the first time; but when I print my pdf file for the second time the app freezes and then crashes.
Below is my code:
NSData *myPdfData = [NSData dataWithContentsOfFile:pdfPath];
UIPrintInteractionController *controller = [UIPrintInteractionController sharedPrintController];
if (controller && [UIPrintInteractionController canPrintData:myPdfData]){
controller.delegate = delegate;
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.outputType = UIPrintInfoOutputGeneral;
printInfo.jobName = [pdfPath lastPathComponent];
printInfo.duplex = UIPrintInfoDuplexLongEdge;
controller.printInfo = printInfo;
controller.showsPageRange = YES;
controller.printingItem = myPdfData;
// We need a completion handler block for printing.
UIPrintInteractionCompletionHandler completionHandler = ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
if(completed && error){
NSLog(#"FAILED! due to error in domain %# with error code %u", error.domain, error.code);
}
};
[controller presentFromRect:[sender frame] inView:senderView animated:YES completionHandler:completionHandler];
}else {
NSLog(#"Couldn't get shared UIPrintInteractionController!");
}
Below is my stack trace from the device:
D
ate/Time: 2011-03-17 20:48:02.523 -0700
OS Version: iPhone OS 4.3 (8F190)
Report Version: 104
Exception Type: 00000020
Exception Codes: 0x8badf00d
Highlighted Thread: 0
Application Specific Information:
Brighton failed to resume in time
Elapsed total CPU time (seconds): 2.310 (user 0.290, system 2.020), 23% CPU
Elapsed application CPU time (seconds): 0.000, 0% CPU
Thread 0 name: Dispatch queue: com.apple.main-thread
Thread 0:
0 libsystem_kernel.dylib 0x30bd2ab0 0x30bc2000 + 68272
1 PrintKit 0x313f2c1a 0x313df000 + 80922
2 PrintKit 0x313ee9ea 0x313df000 + 63978
3 PrintKit 0x313eea90 0x313df000 + 64144
4 PrintKit 0x313eeab4 0x313df000 + 64180
5 PrintKit 0x313e4f96 0x313df000 + 24470
6 PrintKit 0x313e266a 0x313df000 + 13930
7 UIKit 0x335e3656 0x33311000 + 2958934
8 UIKit 0x335e904c 0x33311000 + 2981964
9 UIKit 0x335e8bcc 0x33311000 + 2980812
10 UIKit 0x335e99fc 0x33311000 + 2984444
11 UIKit 0x3343460c 0x33311000 + 1193484
12 Foundation 0x30d306ce 0x30cab000 + 546510
13 CoreFoundation 0x31c43a40 0x31bce000 + 481856
14 CoreFoundation 0x31c45ec4 0x31bce000 + 491204
15 CoreFoundation 0x31c4683e 0x31bce000 + 493630
16 CoreFoundation 0x31bd6ebc 0x31bce000 + 36540
17 CoreFoundation 0x31bd6dc4 0x31bce000 + 36292
18 GraphicsServices 0x32dbf418 0x32dbb000 + 17432
19 GraphicsServices 0x32dbf4c4 0x32dbb000 + 17604
It would be really helpful if anyone could help me figure out the issue.
Thanks in advance!

The clue is in this: "Brighton failed to resume in time."
When printing is finished, control is returned to your app but you take too long to respond. iOS thinks that you've stopped responding to input and kills your app.

Related

EXC_BAD_ACCESS (SIGBUS) on iOS

We are facing iOS crash issue in our one SDK library written in objective-c. This objective-c library is being invoked from swift app developed by our customer.
Following is the code snippet from our sdk, where we are creating multiple threads:-
//Create a queue to collect attributes in parallel
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
//Create group to wait on the task scheduled in global queue
dispatch_group_t group = dispatch_group_create();
// Collect all information1
dispatch_group_async(group, queue, ^{
info1 = [self getInformation1];
});
// Collect all information2
dispatch_group_async(group, queue, ^{
info2 = [self getInformation2];
});
// Collect all information3
dispatch_group_async(group, queue, ^{
info3 = [self getInformation3];
});
// Collect all information4
dispatch_group_async(group, queue, ^{
info4 = [self getInformation4];
});
// Collect all information5
dispatch_group_async(group, queue, ^{
info5 = [self getInformation5];
});
// wait on the group to block the current thread.
int64_t time_delay = 3.0;
dispatch_time_t timeout = dispatch_time(DISPATCH_TIME_NOW, time_delay * NSEC_PER_SEC);
long success = dispatch_group_wait(group,timeout);
if(success != 0) {
//Log data to check which bucket is not complete
[Logger writeLogWithSeverity:kLogERROR message:info1];
[Logger writeLogWithSeverity:kLogERROR message:info2];
[Logger writeLogWithSeverity:kLogERROR message:info3];
[Logger writeLogWithSeverity:kLogERROR message:info4];
[Logger writeLogWithSeverity:kLogERROR message:info5];
}
Is this is ideal way or is there any better way to create concurrent threads?
Following are couple of stack traces of the crashes
1)
Exception Type: EXC_BAD_ACCESS (SIGBUS)
Exception Codes: 0x00000000 at 0x0000000323f7bec8
Crashed Thread: 0
Thread 0 Crashed:
0 libobjc.A.dylib 0x000000018193c1a0 0x181918000 + 147872 (objc_retain + 16)
1 abcMobile 0x0000000104365cbc 0x1041c8000 + 1694908 -[DeviceInventory notifyCollectingdeviceInfo:] (DeviceInventory.m:215 + 28)
2 abcMobile 0x0000000104365b78 0x1041c8000 + 1694584 -[DeviceInventory startCollectingdeviceInfo] (DeviceInventory.m:206 + 0)
3 libdispatch.dylib 0x0000000182058b24 0x182057000 + 6948 ( + 24)
4 libdispatch.dylib 0x0000000182058ae4 0x182057000 + 6884 ( + 16)
5 libdispatch.dylib 0x00000001820656e0 0x182057000 + 59104 ( + 1012)
6 CoreFoundation 0x000000018270f070 0x182621000 + 974960 ( + 12)
7 CoreFoundation 0x000000018270cbc8 0x182621000 + 965576 ( + 2272)
8 CoreFoundation 0x000000018262cda8 0x182621000 + 48552 (CFRunLoopRunSpecific + 552)
9 GraphicsServices 0x000000018460f020 0x184604000 + 45088 (GSEventRunModal + 100)
10 UIKit 0x000000018c60d78c 0x18c2f0000 + 3266444 (UIApplicationMain + 236)
11 abcMobile 0x00000001041ccc40 0x1041c8000 + 19520 main (main.swift:14 + 20)
12 libdyld.dylib 0x00000001820bdfc0 0x1820bd000 + 4032 ( + 4)
Crashing code :- [self.delegate didCompletedCollectingInformation:deviceInfo];
didCompletedCollectingInformation is a call-back function
2)
Exception Type: EXC_BAD_ACCESS (SIGBUS)
Exception Codes: 0x00000000 at 0x00000007943dbec8
Crashed Thread: 18
Thread 18 Crashed:
0 libobjc.A.dylib 0x0000000182f3c1a0 0x182f18000 + 147872 (objc_retain + 16)
1 abcMobile 0x0000000100c0150c 0x100a64000 + 1692940 -[DeviceInventory didFailWithError:] (DeviceInventory.m:144 + 28)
2 CoreFoundation 0x0000000183cf8c3c 0x183c21000 + 883772 ( + 20)
3 CoreFoundation 0x0000000183cf81b8 0x183c21000 + 881080 ( + 428)
4 CoreFoundation 0x0000000183cf7f14 0x183c21000 + 880404 ( + 216)
5 CoreFoundation 0x0000000183d7584c 0x183c21000 + 1394764 ( + 1408)
6 CoreFoundation 0x0000000183c2ef38 0x183c21000 + 57144 (_CFXNotificationPost + 384)
7 Foundation 0x000000018469fbbc 0x184699000 + 27580 ( + 68)
8 abcMobile 0x0000000100bf7f80 0x100a64000 + 1654656 +[Errors sendErrorNotifactionForErrorCode:] (Errors.m:405 + 64)
9 abcMobile 0x0000000100bf101c 0x100a64000 + 1626140 +[NetworkInfo information1] (NetworkInfo.m:711 + 0)
10 abcMobile 0x0000000100bfb9fc 0x100a64000 + 1669628 -[Services information1] (Services.m:391 + 20)
11 abcMobile 0x0000000100c058b4 0x100a64000 + 1710260 -[DeviceInventory getInformation1] (DeviceInventory.m:635 + 56)
12 abcMobile 0x0000000100c0268c 0x100a64000 + 1697420 __39-[DeviceInventory getdeviceInfo]_block_invoke.163 (DeviceInventory.m:256 + 16)
13 libdispatch.dylib 0x0000000183658aa0 0x183657000 + 6816 ( + 24)
14 libdispatch.dylib 0x0000000183658a60 0x183657000 + 6752 ( + 16)
15 libdispatch.dylib 0x000000018369a5f0 0x183657000 + 275952 ( + 1148)
16 libdispatch.dylib 0x000000018369a110 0x183657000 + 274704 ( + 112)
17 libsystem_pthread.dylib 0x000000018398bfac 0x18398b000 + 4012 (_pthread_wqthread + 1176)
Crashing code :- if([self.delegate respondsToSelector:#selector(didFailWithError:)])
Here, didFailWithError is a call-back function
We are unable to find the root cause of this crash as it is very random issue. Does anyone have any idea how to fix this crash issue?
Any pointers will be very helpful as we are struck on this issue.

UIDocument saveToUrl Delayed Crash

I have a Core Data app that's been running fine for over 4 years. Last week I updated XCode to version 8.2.1 (can't remember what I was running before this, but it had been months since I updated it).
After updating, I'm now getting a crash that I can't track down. There's a delay between doing something in the app, and getting the crash to occur. I have attempted to setup global breakpoints to gain more information, but nothing specific is shown that I can tell.
I don't explicitly spawn any threads myself.
When my app first launches, in the viewDidLoad of my initial viewController I do this:
- (void)viewDidLoad
{
[super viewDidLoad];
NSFileManager* fileManager = [NSFileManager defaultManager];
NSURL* ubiquitousURL = [fileManager URLForUbiquityContainerIdentifier:nil];
NSDictionary* localOptions = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],
NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES],
NSInferMappingModelAutomaticallyOption,
nil];
NSURL* localURL = [fileManager URLForDirectory:NSDocumentDirectory
inDomain:NSUserDomainMask
appropriateForURL:nil
create:NO
error:nil];
NSURL* localCoreDataURL = [localURL URLByAppendingPathComponent:#"MyData"];
self.database = [[UIManagedDocument alloc] initWithFileURL:localCoreDataURL];
self.database.persistentStoreOptions = localOptions;
if( [fileManager fileExistsAtPath:[localCoreDataURL path]] )
{
[self.database openWithCompletionHandler: ^(BOOL success) {
//log statement
}];
}
else
{
NSFileCoordinator* coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
[coordinator coordinateWritingItemAtURL:ubiquitousURL
options:NSFileCoordinatorWritingForDeleting
error:nil
byAccessor:^(NSURL *newURL) {
[[NSFileManager defaultManager] removeItemAtURL:newURL error:nil];
}];
[self.database saveToURL:localCoreDataURL
forSaveOperation:UIDocumentSaveForCreating
completionHandler:^(BOOL success) {
//log statement
}];
}
}
Later in the app, I allow the user to create some data and save it (create a new entity), like this:
NSManagedObjectContext* context = database.managedObjectContext;
NSError* error = nil;
if( ![context save:&error])
{
[AppUtility printNsError:error];
[NSException raise:NSInternalInconsistencyException format:#"An error occurred when saving context: %#",[error localizedDescription]];
}
else
{
if (![[context parentContext] save:&error])
{
NSLog(#"Error Saving Parent Data %#, %#", error, [error userInfo]);
}
}
The app will then run for 15 to 20 seconds, then suddenly crash. There is an error in the log that says
[NSError retain]: message sent to deallocated instance 0x608000443b10
And the output in the debug navigator looks like this:
Thread 1 Queue: com.apple.main-thread
0 __forwarding__
1 _forwarding_prep_0__
2 -[UIDocument saveToURL:forSaveOperation:completionHandler:
3 __55-[UIDocument _saveUnsavedChangesWithCompletionHandler:)_block_invoke_2
4 _dispatch_call_block_and_release
5 _dispatch_client_callout ()
6 _dispatch_main_queue_callback_4CF
7 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__
8 __CFRunLoopRun
9 CFRunLoopRunSpecific
10 GSEventRunModal
11 UIApplicationMain
12 main
13 start
14 start
Enqueued from UIDocument File Access (Thread 5)
0 _dispatch_queue_push
1 __55-[UIDocument _saveUnsavedChangesWithCompletionHandler:]_block_invoke
2 _dispatch_call_block_and_release
...
Equeued from com.apple.main-thread (Thread 1)
0 _dispatch_queue_push
1 -[UIDocument _saveUnsavedChangesWithCompletionHandler:]
2 -[UIDocument _autosaveWithCompletionHandler:]
3 +[UIDocument _autosavingTimerDidFireSoContinue:]
4 __NSFireTimer ()
5 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__
...
In an attempt to get more information, I enabled Zombie settings, then ran this in XCode:
command script import lldb.macosx.heap
malloc_info --stack-history *memory address*
The output of that didn't seem to point to a specific line in my app:
(lldb) malloc_info --stack-history 0x60820f611fd0
0x000060820f611fd0: malloc( 48) -> 0x60820f611fd0
_NSZombie_NSError stack[0]: addr = 0x60820f611fd0, type=malloc, frames:
[0] 0x000000010ffcb130 libsystem_malloc.dylib`calloc + 30
[1] 0x000000010ea45458 libobjc.A.dylib`class_createInstance + 85
[2] 0x000000010ea4fd55 libobjc.A.dylib`_objc_rootAlloc + 42
[3] 0x000000010de1f19b Foundation`+[NSError errorWithDomain:code:userInfo:] + 37
[4] 0x000000010c1a4a3c CoreData`-[NSPropertyDescription(_NSInternalMethods) _nonPredicateValidateValue:forKey:inObject:error:] + 124
[5] 0x000000010c1a4bc0 CoreData`-[NSRelationshipDescription(_NSInternalMethods) _nonPredicateValidateValue:forKey:inObject:error:] + 80
[6] 0x000000010c1a3b40 CoreData`-[NSManagedObject(_NSInternalMethods) _validateValue:forProperty:andKey:withIndex:error:] + 384
[7] 0x000000010c1a3896 CoreData`-[NSManagedObject(_NSInternalMethods) _validatePropertiesWithError:] + 358
[8] 0x000000010c1a36f7 CoreData`-[NSManagedObject(_NSInternalMethods) _validateForSave:] + 119
[9] 0x000000010c1b3d4c CoreData`-[NSManagedObject validateForInsert:] + 76
[10] 0x000000010c1a2a77 CoreData`-[NSManagedObjectContext(_NSInternalAdditions) _validateObjects:forOperation:error:exhaustive:forSave:] + 1783
[11] 0x000000010c1a2202 CoreData`-[NSManagedObjectContext(_NSInternalAdditions) _validateChangesForSave:] + 146
[12] 0x000000010c1a1f56 CoreData`-[NSManagedObjectContext(_NSInternalChangeProcessing) _prepareForPushChanges:] + 214
[13] 0x000000010c19e972 CoreData`-[NSManagedObjectContext save:] + 562
[14] 0x000000010ce26a9d UIKit`__43-[UIManagedDocument contentsForType:error:]_block_invoke + 30
[15] 0x000000010c1b89a7 CoreData`developerSubmittedBlockToNSManagedObjectContextPerform + 199
[16] 0x000000010c1b885f CoreData`-[NSManagedObjectContext performBlockAndWait:] + 255
[17] 0x000000010ce269f0 UIKit`-[UIManagedDocument contentsForType:error:] + 258
[18] 0x000000010cd9477c UIKit`-[UIDocument saveToURL:forSaveOperation:completionHandler:] + 486
[19] 0x000000010cd962b2 UIKit`__55-[UIDocument _saveUnsavedChangesWithCompletionHandler:]_block_invoke_2 + 156
[20] 0x000000010fd77978 libdispatch.dylib`_dispatch_call_block_and_release + 12
[21] 0x000000010fda10cd libdispatch.dylib`_dispatch_client_callout + 8
[22] 0x000000010fd818a4 libdispatch.dylib`_dispatch_main_queue_callback_4CF + 406
[23] 0x000000010ef9de49 CoreFoundation`__CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
[24] 0x000000010ef6337d CoreFoundation`__CFRunLoopRun + 2205
[25] 0x000000010ef62884 CoreFoundation`CFRunLoopRunSpecific + 420
[26] 0x00000001115dfa6f GraphicsServices`GSEventRunModal + 161
[27] 0x000000010c5a1c68 UIKit`UIApplicationMain + 159
[28] 0x000000010bac23bf MyApp`main + 111 at main.m:16:9
[29] 0x000000010fded68d libdyld.dylib`start + 1
[30] 0x0000000110153001 libsystem_pthread.dylib`_thread + 1
Can someone help me diagnose this?

iOS Crash Log NSObject doesNotRecognizeSelector: - at which line?

I have recorded a crash of my app, but the last line in my app (5 Control) points just to the method begin. How do I know in which line the problem is?
0 CoreFoundation 0x185f0af50 __exceptionPreprocess + 132
1 libobjc.A.dylib 0x1924141fc objc_exception_throw + 60
2 CoreFoundation 0x185f0fc04 -[NSObject(NSObject) doesNotRecognizeSelector:] + 220
3 CoreFoundation 0x185f0d930 ___forwarding___ + 912
4 CoreFoundation 0x185e2d5dc _CF_forwarding_prep_0 + 92
5 Control 0x10005acb4 -[PaymillPaymentService handleTransactionListRequest:] (PaymillPaymentService.m:211)
6 Foundation 0x186a7416c __103+[__NSOperationInternal _observeValueForKeyPath:ofObject:changeKind:oldValue:newValue:indexes:context:]_block_invoke96 + 28
7 libdispatch.dylib 0x1929ec014 _dispatch_call_block_and_release + 24
8 libdispatch.dylib 0x1929ebfd4 _dispatch_client_callout + 16
9 libdispatch.dylib 0x1929f32b8 _dispatch_root_queue_drain + 556
10 libdispatch.dylib 0x1929f34fc _dispatch_worker_thread2 + 76
11 libsystem_pthread.dylib 0x192b816bc _pthread_wqthread + 356
12 libsystem_pthread.dylib 0x192b8154c start_wqthread + 4
Here the [lengthy] method code. I see a couple of places where I can add the check but how to I know it for sure that I fixed the issue? The problem is sporadical and I cannot reproduce it easily.
- (void)handleTransactionListRequest:(ServiceRequest *)serviceRequest
{
LRURLRequestOperation* operation = serviceRequest.operation;
NSHTTPURLResponse *response = (NSHTTPURLResponse *)operation.URLResponse;
if (response.statusCode == 200)
{
if (operation.responseData)
{
NSError *parserError = nil;
NSDictionary *data = [NSJSONSerialization JSONObjectWithData:operation.responseData options:0 error:&parserError];
//NSLog(#"%#", data);
if (!parserError)
{
NSArray* transactions = [data objectForKey:#"data"];
if (0 == serviceRequest.currentOffset)
{
NSNumber* totalCountObj = [data objectForKey:#"data_count"];
serviceRequest.totalCount = [totalCountObj intValue];
}
int loadedCount = 0;
if (transactions)
{
for (id object in transactions)
{
TransactionInfo* info = [self createTransactionFrom:object];
[serviceRequest.transactionList addTransaction:info];
[info release];
loadedCount++;
}
}
if (loadedCount + serviceRequest.currentOffset >= serviceRequest.totalCount)
{
if ([serviceRequest.delegate respondsToSelector:#selector(transactionListLoadingComplete:)])
[serviceRequest.delegate transactionListLoadingComplete:serviceRequest];
serviceRequest.transactionList.timeStamp = [[NSDate date] timeIntervalSince1970];
NSLog(#"COMPLETE: %d transaction loaded ", serviceRequest.totalCount);
}
else
{
serviceRequest.currentOffset += loadedCount;
bool needToContinue = YES;
if ([serviceRequest.delegate respondsToSelector:#selector(transactionListLoadingContinue:)])
needToContinue = [serviceRequest.delegate transactionListLoadingContinue];
if (needToContinue)
{
[self continueRetrievingTransactionListFor:serviceRequest];
NSLog(#"CONTINUE: %d of %d loaded ", serviceRequest.currentOffset, serviceRequest.totalCount);
}
}
return; // all OK cases
}
}
}
if ([serviceRequest.delegate respondsToSelector:#selector(transactionListLoadingFailed:with:)])
[serviceRequest.delegate transactionListLoadingFailed:serviceRequest with:response.statusCode];
NSLog(#"ERROR: Loading Transactions Response Code: %ld", (long)response.statusCode);
}
Short Answer:
You are sending a message to an object that cannot validly respond to it. The stack trace is telling you that when you make the call [PaymillPaymentService handleTransactionListRequest:] that PaymillPaymentService cannot accept handleTransactionListRequest.
Long answer:
Look at the stack trace here:
5 Control 0x10005acb4 -[PaymillPaymentService handleTransactionListRequest:] (PaymillPaymentService.m:211)
This is telling you that in the file PaymillPaymentService.m on line 211 you are sending PaymillPaymentService the message handleTransactionListRequest to which it cannot validly respond. In your discussion with rmaddy, Hot Licks, and Paulc11 you mentioned that line 211 is the function entry for handleTransactionListRequest (in whatever file it resides). If that's the case it is coincidental.
If you want further follow up you need to post PaymillPaymentService.m and ensure that you include all the line numbers.

RestKit Paginator Crash: Cannot determine hasNextPage: paginator is not loaded

For some reason, I randomly sometimes get this crash.
Fatal Exception: NSInternalInconsistencyException
Cannot determine hasNextPage: paginator is not loaded.
Thread : Fatal Exception: NSInternalInconsistencyException
0 CoreFoundation 0x309a1f4b __exceptionPreprocess + 130
1 libobjc.A.dylib 0x3b1386af objc_exception_throw + 38
2 CoreFoundation 0x309a1e25 +[NSException raise:format:]
3 Foundation 0x31349fe3 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 90
4 Poka 0x004f0f71 -[RKPaginator hasNextPage] (RKPaginator.m:151)
5 Poka 0x00289a41 __66-[PokaLocationContentManagerSingleton fetchLatestPlantsWithCount:]_block_invoke (PokaLocationContentManagerSingleton.m:345)
6 Poka 0x004f2495 __24-[RKPaginator loadPage:]_block_invoke157 (RKPaginator.m:231)
7 Poka 0x004e9355 __66-[RKObjectRequestOperation setCompletionBlockWithSuccess:failure:]_block_invoke244 (RKObjectRequestOperation.m:477)
8 libdispatch.dylib 0x3b61bd1b _dispatch_call_block_and_release + 10
9 libdispatch.dylib 0x3b61bd07 _dispatch_client_callout + 22
10 libdispatch.dylib 0x3b62278d _dispatch_main_queue_callback_4CF$VARIANT$mp + 268
11 CoreFoundation 0x3096c819 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 8
12 CoreFoundation 0x3096b0ed __CFRunLoopRun + 1300
13 CoreFoundation 0x308d5c27 CFRunLoopRunSpecific + 522
14 CoreFoundation 0x308d5a0b CFRunLoopRunInMode + 106
15 GraphicsServices 0x355c9283 GSEventRunModal + 138
16 UIKit 0x33179049 UIApplicationMain + 1136
17 Poka 0x0006df95 main (main.m:17)
18 libdyld.dylib 0x3b640ab7 start + 2
I am loading the Paginator like this:
- (void)fetchLatestPlantsWithCount:(NSNumber *)count
{
RKObjectManager *objectManager = [RKObjectManager sharedManager];
NSString *requestString = [NSString stringWithFormat:#"/api/rest/plants/?count=%#&limit=:perPage&offset=:offset", count];
NSDictionary *parameters = nil;
if(_dateFilterLastModifiedAppend)
parameters = [[NSDictionary alloc]initWithObjectsAndKeys:_dateFilterLastModifiedAppend, #"last_modified_date__gte", nil];
RKPaginator *paginator = [objectManager paginatorWithPathPattern:requestString parameters:parameters];
paginator.perPage = API_PER_PAGE_LIMIT;
[ZAActivityBar showWithStatus:[NSString stringWithFormat:NSLocalizedStringFromTable(#"Downloading latest plants: %# remaining", #"PokaLocalizable", nil), count]];
[paginator setCompletionBlockWithSuccess:^(RKPaginator *paginator, NSArray *objects, NSUInteger page) {
if([paginator hasNextPage])
{
[ZAActivityBar showWithStatus:[NSString stringWithFormat:NSLocalizedStringFromTable(#"Downloading latest plants: %# remaining", #"PokaLocalizable", nil), [NSNumber numberWithInt:([count integerValue] - paginator.offset)]]];
[paginator loadNextPage];
}
else
{
[self fetchLatestProductionLinesCount];
}
} failure:^(RKPaginator *paginator, NSError *error) {
[self fetchLatestProductionLinesCount];
}];
[paginator loadPage:1];
}
Finally, I added some code to RestKit in order to load the paginator. I don't think it is the problem though.
- (RKPaginator *)paginatorWithPathPattern:(NSString *)pathPattern parameters:(NSDictionary *)parameters
{
NSAssert(self.paginationMapping, #"Cannot instantiate a paginator when `paginationMapping` is nil.");
NSMutableURLRequest *request = [self requestWithMethod:#"GET" path:pathPattern parameters:parameters];
RKPaginator *paginator = [[RKPaginator alloc] initWithRequest:request paginationMapping:self.paginationMapping responseDescriptors:self.responseDescriptors];
#ifdef _COREDATADEFINES_H
paginator.managedObjectContext = self.managedObjectStore.mainQueueManagedObjectContext;
paginator.managedObjectCache = self.managedObjectStore.managedObjectCache;
paginator.fetchRequestBlocks = self.fetchRequestBlocks;
#endif
paginator.operationQueue = self.operationQueue;
Class HTTPOperationClass = [self requestOperationClassForRequest:request fromRegisteredClasses:self.registeredHTTPRequestOperationClasses];
if (HTTPOperationClass) [paginator setHTTPOperationClass:HTTPOperationClass];
return paginator;
}
The only difference is that I pass some parameters to it.
The thing I don't understand is that I load other objects, WITH that same code with the only difference being the type of objects I am downloading. I execute almost that same code right before executing this one, and it works perfectly fine. Hence, my question as to I am confused...
Some more information:
It says the object count is 1, that page is 1, but apparently it is not loaded?
Note that I call the paginator multiple times within the same page. I do the paginator for one type of objects... once it is done I do it for another one... and so on.
All pull requests that I mentioned before were merged already to master. So just use the newest version.
I found an issue and fixed it if you are interested. I posted Pull Request on RestKit github page
https://github.com/RestKit/RestKit/pull/2156
I would recommend to use my fork on branch inventorum where I also cherry picked malloc error fix:
https://github.com/bimusiek/RestKit/commits/inventorum

Why my [UIScrollView removeFromSuperview] is crashing?

The crash log is below.
Do you know any particular reason why might [UIScrollView removeFromSuperview] can crash? The scrollview contains view hierarchy with different types of UIViews. I also finds that the ad hoc version crash often not the debug version. I could not find any reason for that.
Same viewcontroller is loaded in a different flow in iPhone that works fine. But in iPad it crashes.
In iPad, in a container view controller, only viewcontroler.view is loaded.
Incident Identifier: EE102239-34D1-4BE7-8B52-41F74AB26203
CrashReporter Key: 2b11ea2a01ac5618e199ffc5a1e1f321600bb6a9
Hardware Model: iPad3,4
Version: ??? (???)
Code Type: ARM (Native)
Parent Process: launchd [1]
Date/Time: 2013-06-18 15:19:16.132 +0200
OS Version: iOS 6.1.3 (10B329)
Report Version: 104
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x00000000
Crashed Thread: 0
Thread 0 name: Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0 libobjc.A.dylib 0x3bab7070 prepareForMethodLookup + 20
1 libobjc.A.dylib 0x3bab6fb2 lookUpMethod + 42
2 libobjc.A.dylib 0x3bab6f7e _class_lookupMethodAndLoadCache3 + 14
3 libobjc.A.dylib 0x3bab6638 objc_msgSend_uncached + 24
4 QuartzCore 0x357f2a72 CA::Layer::contents_visibility_changed(CA::Transaction*, bool) + 50
5 QuartzCore 0x357f29de CA::Layer::mark_visible(CA::Transaction*, bool) + 190
6 QuartzCore 0x357f29b2 CA::Layer::mark_visible(CA::Transaction*, bool) + 146
7 QuartzCore 0x357f29b2 CA::Layer::mark_visible(CA::Transaction*, bool) + 146
8 QuartzCore 0x357f29b2 CA::Layer::mark_visible(CA::Transaction*, bool) + 146
9 QuartzCore 0x357f29b2 CA::Layer::mark_visible(CA::Transaction*, bool) + 146
10 QuartzCore 0x357f28d2 CA::Layer::update_removed_sublayer(CA::Transaction*, unsigned int) + 18
11 QuartzCore 0x357f255a CA::Layer::remove_sublayer(CA::Transaction*, CALayer*) + 130
12 QuartzCore 0x357f246a CA::Layer::remove_from_superlayer() + 34
13 UIKit 0x35a6e92c -[UIView(Hierarchy) removeFromSuperview] + 144
14 UIKit 0x35b857bc -[UIScrollView removeFromSuperview] + 60
15 MyApp 0x000bde8a -[iPadNavigationController vcAnimationDone] (iPadNavigationController.m:400)
16 UIKit 0x35a55ab6 -[UIViewAnimationState sendDelegateAnimationDidStop:finished:] + 154
17 UIKit 0x35aca8f8 -[UIViewAnimationState animationDidStop:finished:] + 44
18 QuartzCore 0x35801304 CA::Layer::run_animation_callbacks(void*) + 204
19 libdispatch.dylib 0x3bed55d8 _dispatch_client_callout + 20
20 libdispatch.dylib 0x3bed8e40 _dispatch_main_queue_callback_4CF + 224
21 CoreFoundation 0x33c051ac __CFRunLoopRun + 1284
22 CoreFoundation 0x33b78238 CFRunLoopRunSpecific + 352
23 CoreFoundation 0x33b780c4 CFRunLoopRunInMode + 100
24 GraphicsServices 0x37733336 GSEventRunModal + 70
25 UIKit 0x35a942b4 UIApplicationMain + 1116
A few line from the code (as asked),
previous = showing;
showing = [ vc retain ];
showing.view.frame = startFrameIn;
[ container addSubview:showing.view ];
CGContextRef context = UIGraphicsGetCurrentContext();
[ UIView beginAnimations:nil context:context ];
[ UIView setAnimationDelegate:self ];
[ UIView setAnimationDidStopSelector:#selector(vcAnimationDone) ];
[ UIView setAnimationCurve:UIViewAnimationCurveEaseOut ];
[ UIView setAnimationDuration:0.4 ];
previous.view.frame = endFrameOut;
showing.view.frame = detailFrame;
[ UIView commitAnimations ];
}
- (void) vcAnimationDone {
if ( previous != nil ) {
if (previous.view.superview != nil) {
[previous.view removeFromSuperview];
}
[ previous release ];
previous = nil;
}
A very probable reason is that you are overreleasing your scrollview or one of the views inside it.
Calling removeFromSuperview then deallocates the view instead of simply decreasing the retain count.
Actually, if you are still stuck with non-ARC project, Static Code Analysis is very useful for this kind of bug. Retain/release balancing issues are hard to pin down, and nearly impossible with incomplete method so I suggest you post the full method body if possible.
Thanks everyone for your answers, tips and tricks. However one thing I want share with you is the cause of the crash. I found that the crash was at different thread in different times. I had several views loaded with button pressing/menu in my iPad app. Some of the button pressing fetch data from web service. So I was bit confused to get the cuase of crash, animation, or url connection etc... I tried with enabled NSZombie objects, but it did not show any information.
Then I tried with Guard Malloc. This only runs in Simulator. And magically I found the code point of crash. I have function to convert a hex string into data. There I have line of code to make a C string null terminated. where I assigned 0 at the last index. and that makes the crash!
tmpCh[count] = 0;
I do not why, but probably it takes some time in the memory management procedure in iOS so it crash at different thread at different times. But with Guard malloc in Simulator, it always point out here and when I rewrite the code, the crash is gone.
/* Converts a hex string to bytes.
Precondition:
. The hex string can be separated by space or not.
. the string length without space or 0x, must be even. 2 symbols for one byte/char
. sample input: 23 3A F1 OR 233AF1
*/
+ (NSData *) dataFromHexString:(NSString*)hexString
{
if (hexString.length < 1) {
return nil;
}
char * tmpCh = (char *) malloc([hexString length] * sizeof(char));
int count = 0;
for (int k=0; k<hexString.length;k++) {
char c = [hexString characterAtIndex:k];
if (c == (char)0x20) { //skip space
continue;
}
if (c == '0') { // skip 0x
if(k+1 < hexString.length){
if ([hexString characterAtIndex:k+1] == 'x'
|| [hexString characterAtIndex:k+1] == 'X' )
{
k = k + 1;
continue;
}
}
}
tmpCh[count] = c;
count++;
}
tmpCh[count] = 0; // make null terminated string
if (count % 2) {
return nil;
}
NSString *temp = [[NSString alloc] initWithUTF8String:tmpCh];
free(tmpCh);
if ([temp length] % 2 != 0) {
return nil;
}
NSMutableData *result = [[NSMutableData alloc] init];
unsigned char byte;
char hexChars[3] = {0};
for (int i=0; i < (temp.length/2); i++) {
hexChars[0] = [temp characterAtIndex:i*2];
hexChars[1] = [temp characterAtIndex:i*2+1];
if (![Util isValidChar:hexChars[0]] || ![Util isValidChar:hexChars[1]]) {
return nil;
}
byte = strtol(hexChars, NULL, 16);
[result appendBytes:&byte length:1];
}
NSData * data = [NSData dataWithData:result];
[result release];
return data;
}

Resources