Why my [UIScrollView removeFromSuperview] is crashing? - ios

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;
}

Related

backtrace miss the function that caused a crash

I use backtrace and backtrace_symbols to collect the call stack when my app crashed.
void InstallSignalHandler(void)
{
signal(SIGHUP, SignalExceptionHandler);
signal(SIGINT, SignalExceptionHandler);
signal(SIGQUIT, SignalExceptionHandler);
signal(SIGABRT, SignalExceptionHandler);
signal(SIGILL, SignalExceptionHandler);
signal(SIGSEGV, SignalExceptionHandler);
signal(SIGFPE, SignalExceptionHandler);
signal(SIGBUS, SignalExceptionHandler);
signal(SIGPIPE, SignalExceptionHandler);
}
void SignalExceptionHandler(int signal)
{
NSMutableString *mstr = [[NSMutableString alloc] init];
[mstr appendString:#"Stack:\n"];
void* callstack[128];
int i, frames = backtrace(callstack, 128);
char** strs = backtrace_symbols(callstack, frames);
for (i = 0; i <frames; ++i) {
[mstr appendFormat:#"%s\n", strs[i]];
}
NSLog(#"%#", mstr);
free(strs);
}
When I check the log in console, I just find the log miss the function that caused the crash.The function is:
+ (void)testCrash
{
int *nullPointer = NULL;
*nullPointer = 2019;
}
And the log in console is:
0 TestApp 0x0000000101d1e040 SignalExceptionHandler + 160
1 libsystem_platform.dylib 0x000000011002bb5d _sigtramp + 29
2 ??? 0x0000000000000000 0x0 + 0
3 TestApp 0x00000001019bbc6f __39+[MyCrashTesting showInViewController:]_block_invoke + 303
4 UIKit 0x000000010b09a559 -[UIAlertController _invokeHandlersForAction:] + 105
5 UIKit 0x000000010b09af5e __103-[UIAlertController _dismissAnimated:triggeringAction:triggeredByPopoverDimmingView:dismissCompletion:]_block_invoke.461 + 16
6 UIKit 0x000000010ae42ca2 -[UIPresentationController transitionDidFinish:] + 1346
7 UIKit 0x000000010ae46b12 __56-[UIPresentationController runTransitionForCurrentState]_block_invoke.436 + 183
8 UIKit 0x000000010ba2a3b4 -[_UIViewControllerTransitionContext c
I have thought the function name "testCrash" should be in the top of the log. Does I do something wrong?
Since this is a very simple method with no arguments and no ARC heavylifting inside clang the Objective-C compiler is able to do an optimization (-O1 is enough to achieve that) of removing the message runtime call.
You can prevent this behavior with:
+ (void)testCrash __attribute__((optnone))
{
int *nullPointer = NULL;
*nullPointer = 2019;
}
The lesson learnt here is you should never rely on particular stacktrace to achieve something during your program execution. Diagnostics is fine as long as you understand the optimizing principles you've just encountered.

Crash on iOS 8 when dispatch_group_wait() return because of timeout

I have two operations fetching a value. I only care about the sum both values. And I don't care about the value at all if it takes too long.
So I thought it would be an easy task for GCD using groups. Unfortunately, the below code only works fine on iOS 9. Each time I have no matching calls of dispatch_group_enter()/dispatch_group_leave() I get a crash.
The documentation states clearly that I have to match both call. But when I use a timeout on dispatch_group_wait(), it is impossible to have the same amount of leave calls as enter calls; that is the whole point of specifying a timeout.
So is this a known bug in iOS 8? Am I doing something wrong? Is there another solution to my initial problem that works on iOS 8 as well?
EDIT: Actually we can boil it down to this:
var sync_group: dispatch_group_t = dispatch_group_create();
dispatch_group_enter(sync_group);
let maxWait = dispatch_time(DISPATCH_TIME_NOW, Int64(60 * NSEC_PER_SEC))
let result = dispatch_group_wait(sync_group, maxWait)
sync_group = dispatch_group_create();
Works as expected on iOS 9 but does crash on iOS 8 on the last line because the old dispatch_group_t instance can not be release. Any easy workarounds?
EDIT 2: Turns out it is broken on iOS 9.0 too. It only works as as it should in iOS 9.1+.
Original Code:
let qualityOfServiceClass = QOS_CLASS_BACKGROUND
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
dispatch_async(backgroundQueue, {
/* We want this method to block until the network code succeeded. */
let sync_group: dispatch_group_t = dispatch_group_create();
/* Start async operation 1. */
dispatch_group_enter(sync_group);
self.someAsyncOperation1({(value: Int, finalValue: Bool) in
if (finalValue) {
valOp1 = value
dispatch_group_leave(sync_group);
}
})
/* Start async operation 2. */
dispatch_group_enter(sync_group);
self.someAsyncOperation2({(value: Int, finalValue: Bool) in
if (finalValue) {
valOp2 = value
dispatch_group_leave(sync_group)
}
})
/* Block current thread until all leaves were called. If it takes more then 60 sec we don't care and let go. */
let maxWait = dispatch_time(DISPATCH_TIME_NOW, Int64(60 * NSEC_PER_SEC))
let result = dispatch_group_wait(sync_group, maxWait)
if (result > 0) {
/* This will result in a crash when we leave the scope: SIGTRAP in dispatch_semaphore_dispose */
return
}
dispatch_async(dispatch_get_main_queue(), {
let newValue = valOp1 + valOp2
self.lastKnownNotificationCombinedCounter = newValue
success(newValue)
})
})
The actual crash loops like that:
Exception Type: SIGTRAP
Exception Codes: #0 at 0x3958a2a4
Thread 2 Crashed:
0 libdispatch.dylib 0x3958a2a4 _dispatch_semaphore_dispose$VARIANT$mp + 48
1 libdispatch.dylib 0x3958b491 _dispatch_dispose$VARIANT$mp + 30
2 libdispatch.dylib 0x3957ea8f -[OS_dispatch_object _xref_dispose] + 44
3 myApp 0x00176a24 block_destroy_helper67 + 354
4 myApp 0x00176ab8 0x2e000 + 1346232
5 myApp 0x00178334 0x2e000 + 1352500
6 libsystem_blocks.dylib 0x395d3adb _Block_release + 216
7 Foundation 0x2c4143b9 -[NSBlockOperation dealloc] + 58
8 libobjc.A.dylib 0x39036d57 objc_object::sidetable_release(bool) + 164
9 libobjc.A.dylib 0x390371a9 (anonymous namespace)::AutoreleasePoolPage::pop(void*) + 402
10 libdispatch.dylib 0x39589423 _dispatch_root_queue_drain + 1176
11 libdispatch.dylib 0x3958a1fb _dispatch_worker_thread3 + 104
12 libsystem_pthread.dylib 0x396fae25 _pthread_wqthread + 666
13 libsystem_pthread.dylib 0x396fab78 start_wqthread + 6
I came up with this workaround:
private let MAX_TRIES = 20;
func dispatch_group_wait_ios8Safe(group: dispatch_group_t, _ timeout: dispatch_time_t) -> Int {
if #available(iOS 9, *) {
/* Just forward the call. */
return dispatch_group_wait(group, timeout)
} else {
/* Forward the call to original function and store result. */
let firstResult = dispatch_group_wait(group, timeout)
var result = firstResult, tries = 0
while(result > 0 && tries < MAX_TRIES) {
dispatch_group_leave(group)
result = dispatch_group_wait(group, DISPATCH_TIME_NOW)
tries += 1
}
/* Return original result. */
return firstResult
}
}
So until someone comes up with a better solution I stick with 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

Xcode 4 and "SIGABRT" error? (only for iphone though)

I'm new to ios development and to stackoverflow. I did try searching both stackoverflow and google before posting.
I built a simple little app, originally just left it an iphone only app, but decided to make it universal in the end. I, stupidly, was messing around when i was getting to know xcode 4 and switched it to universal and then back again so i had to recopy the project and do it again. This time i started it with a universal app. (Not when i created it but after i went to project and selected it there) It created the ipad folder and mainwindow-ipad.xib file but was empty of course since i didn't do anything yet. I had it set up as a tabbed based app so my iphone version had firstview and secondview nib files also, but the ipad version didn't. I set it all up in iphone version first and it worked fine. I then went and laid down the ipad version (i did eliminate the second tab from mainwindow-ipad because i didn't need it)
i then went and created a new nib file and placed it in the ipad folder along with "main-ipad.h" and "main-ipad.m". I copied my code and connected everything and it runs fine on ipad simulator but now when i try and run iphone simulator i get "SIGABRT error. I took a screen shot of it. I don't fully understand objective-c so i was hoping someone can help me? I can post any code or whatever you might need to help me with this error so just ask.
Appreciate any help and suggestions you may have!
Thanks!
[Okay i would have posted image but I can't since I'm a new user, instead i posted the line highlighted and the output from xcode]
Code for file with error:
int main(int argc, char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil); //ERROR IS ON THIS LINE <-----
[pool release];
return retVal;
}
[OUTPUT]
2011-06-18 17:32:43.980 Price Assist[445:207] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIViewController 0x4e09cc0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key finallabel.'
*** Call stack at first throw:
(
0 CoreFoundation 0x00dc35a9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x00f17313 objc_exception_throw + 44
2 CoreFoundation 0x00dc34e1 -[NSException raise] + 17
3 Foundation 0x00795677 _NSSetUsingKeyValueSetter + 135
4 Foundation 0x007955e5 -[NSObject(NSKeyValueCoding) setValue:forKey:] + 285
5 UIKit 0x0021130c -[UIRuntimeOutletConnection connect] + 112
6 CoreFoundation 0x00d398cf -[NSArray makeObjectsPerformSelector:] + 239
7 UIKit 0x0020fd23 -[UINib instantiateWithOwner:options:] + 1041
8 UIKit 0x00211ab7 -[NSBundle(UINSBundleAdditions) loadNibNamed:owner:options:] + 168
9 UIKit 0x000c7628 -[UIViewController _loadViewFromNibNamed:bundle:] + 70
10 UIKit 0x000c5134 -[UIViewController loadView] + 120
11 UIKit 0x000c500e -[UIViewController view] + 56
12 UIKit 0x00038d42 -[UIWindow addRootViewControllerViewIfPossible] + 51
13 Foundation 0x007955e5 -[NSObject(NSKeyValueCoding) setValue:forKey:] + 285
14 UIKit 0x00048ff6 -[UIView(CALayerDelegate) setValue:forKey:] + 173
15 UIKit 0x0021130c -[UIRuntimeOutletConnection connect] + 112
16 CoreFoundation 0x00d398cf -[NSArray makeObjectsPerformSelector:] + 239
17 UIKit 0x0020fd23 -[UINib instantiateWithOwner:options:] + 1041
18 UIKit 0x00211ab7 -[NSBundle(UINSBundleAdditions) loadNibNamed:owner:options:] + 168
19 UIKit 0x0001717a -[UIApplication _loadMainNibFile] + 172
20 UIKit 0x00017cf4 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 291
21 UIKit 0x00022617 -[UIApplication handleEvent:withNewEvent:] + 1533
22 UIKit 0x0001aabf -[UIApplication sendEvent:] + 71
23 UIKit 0x0001ff2e _UIApplicationHandleEvent + 7576
24 GraphicsServices 0x00ffc992 PurpleEventCallback + 1550
25 CoreFoundation 0x00da4944 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
26 CoreFoundation 0x00d04cf7 __CFRunLoopDoSource1 + 215
27 CoreFoundation 0x00d01f83 __CFRunLoopRun + 979
28 CoreFoundation 0x00d01840 CFRunLoopRunSpecific + 208
29 CoreFoundation 0x00d01761 CFRunLoopRunInMode + 97
30 UIKit 0x000177d2 -[UIApplication _run] + 623
31 UIKit 0x00023c93 UIApplicationMain + 1160
32 Price Assist 0x000029a9 main + 121
33 Price Assist 0x00002925 start + 53
)
terminate called after throwing an instance of 'NSException'
iPhone FirstView nib file .h code:
#interface FirstViewController : UIViewController {
IBOutlet UITextField *dollarinput;
IBOutlet UITextField *centsinput;
IBOutlet UIButton *combinevalue;
IBOutlet UITextField *percentoffinput;
IBOutlet UILabel *discountlabel;
IBOutlet UILabel *finallabel;
}
- (IBAction)calculate:(id)sender;
- (IBAction)backgroundTouched:(id)sender;
- (IBAction)autonext:(id)sender;
iPhone FirstView nib file .m code:
//
// FirstViewController.m
// Price Assist
//
// Created by Dustin Schreiber on 6/15/11.
// Copyright 2011 TheTechSphere.com. All rights reserved.
//
#import "FirstViewController.h"
#implementation FirstViewController
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
}
*/
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc. that aren't in use.
}
- (void)viewDidUnload
{
[percentoffinput release];
percentoffinput = nil;
[discountlabel release];
discountlabel = nil;
[finallabel release];
finallabel = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc
{
[percentoffinput release];
[discountlabel release];
[finallabel release];
[super dealloc];
}
- (IBAction)calculate:(id)sender {
if ([centsinput.text length] == 0){
centsinput.text = #"00";
}
if ([dollarinput.text length] == 0){
dollarinput.text = #"00";
}
if ([percentoffinput.text length] == 0){
percentoffinput.text = #"00";
}
double cDollars = [dollarinput.text doubleValue];
double cCents = [centsinput.text doubleValue];
double percentoff = [percentoffinput.text doubleValue] / 100;
NSString *ccDollars = [[NSNumber numberWithFloat:cDollars] stringValue];
NSString *ccCents = [[NSNumber numberWithFloat:cCents] stringValue];
NSString *placeholder = [NSString stringWithFormat:#"%#.%#", ccDollars, ccCents];
double combined = [placeholder doubleValue];
double discount = combined * percentoff;
NSString *discountholder2 =[NSString stringWithFormat:#"%.2f", discount];
discountlabel.text = discountholder2;
double newprice = (combined - discount);
NSString *str = [NSString stringWithFormat:#"%.2f", newprice];
finallabel.text = str;
dollarinput.text = ccDollars;
centsinput.text = ccCents;
percentoffinput.text = [[NSNumber numberWithFloat:percentoff] stringValue];
}
-(IBAction)backgroundTouched:(id)sender
{
[dollarinput resignFirstResponder];
[centsinput resignFirstResponder];
[percentoffinput resignFirstResponder];
}
- (IBAction)autonext:(id)sender {
if ([centsinput.text length ] >= 2) {
if ([centsinput.text length] > 2) {
centsinput.text = #"";
} else {
//next field
}
}
}
#end
Thanks again! If anyone has any suggestions for my code i'd love to here them! Like I said, I'm new to it and thats the only way i know to do this.
------------> If anyone wants, I'll upload the entire project folder. Just ask. Thank you guys for all the help. i'm a n00b with xcode so i haven't got it all down yet.
Project Zipped
Post some code where you use finallabel and try to debug your app so you can tell me the line just before the app crashes.
Option 2:
Try to set a BreakPoint in malloc_error_break so we can have more info about the error.
In XCode go to Run -> Show -> BreakPoints (or just cmd + option + B). Then double click to add a new symbol (symbolic breakpoint) and type in malloc_error_break then press enter.
Now run your app and paste your console text.
UPDATE If you need help http://developer.apple.com/library/mac/#recipes/xcode_help-breakpoint_navigator/articles/adding_a_symbolic_breakpoint.html
Check your connections inside your InterfaceBuilder, you may have it wrong with fianllabel.
Also check your Custom Class -> Class in your iphone XIB in your InterfaseBuilder
UPDATE
Go to Product -> Clean. Then Run.
The line UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); just means that an exception was thrown during the running of your program. This could range from a memory problem, to a simple runtime error. Look in the target debugger console; it will tell you where the error occurred.
Open "iOS Simulator" Menu in the upper left->Reset Content and Settings. Then quit the iOS simulator and Xcode, and then restart your computer. This will get rid of the other instance of the process.
This May work it's work for me...........
The problem is with your XIB file. This error generally occurs when your finalLabel is incorrectly hooked up or doesn't exist anymore. Check your connections in the Interface Builder once.
I also had this error. After spending so much time, I found how to fix it. First of all go the console and see where is the error (mine was related to storyboards and its code) The way I fixed my error was by going in story board. Below the iPhone screen, there will be small yellow button. Right click on it and you will see that is causing error. Delete(x) it if there is yellow error sign.
If this does not fix your error then try to make new project and then replace its blank files with old files of your old project. I had same error in very beginning and by doing this program run without any error.
Other people suggests by restarting your laptop and running it again, reseting the iOS simulator, or changing iOS debugger (however this does not work in latest x code since there is only one debugger)
Hope this helps

Resources