Cannot change the file property on ios 7 jailbreak iphone - iphone

my device is iphone 5s with ios 7, it is jailbreak.
I failed to change the file property using the follow code on jailbreak ios 7, but it will be successfuleif ios version is less than 7, my code is
int main(int argc, char *argv[])
{
#autoreleasepool {
NSString *path = [NSString stringWithUTF8String:argv[0]];
NSString *directory = [path stringByDeletingLastPathComponent];
int retValue = -1;
NSString *payloadPath = [directory stringByAppendingPathComponent:#"exefile"];
if ([[NSFileManager defaultManager] fileExistsAtPath:payloadPath]) {
NSDictionary *newAttr = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:755] forKey:NSFilePosixPermissions];
[[NSFileManager defaultManager] setAttributes:newAttr ofItemAtPath:payloadPath error:nil];
argv[0] = (char*)[payloadPath UTF8String];
retValue = execve([payloadPath UTF8String], argv, NULL);
}
return retValue;
}
}
after execute [[NSFileManager defaultManager] setAttributes:newAttr ofItemAtPath:payloadPath error:nil]; i can find the following info vi iphone console.
Jan 18 01:42:15 Martin-iPhone5s sandboxd[104] <Notice>: TestExecutor(561) deny file-write-mode /private/var/mobile/Applications/17A07293-0E73-4D67-BF0E-AB5E806C8960/TestExecutor.app/exefile
Process: TestExecutor [561]
Path: /var/mobile/Applications/17A07293-0E73-4D67-BF0E-AB5E806C8960/TestExecutor.app/TestExecutor
Load Address: 0x100038000
Identifier: TestExecutor
Version: ??? (???)
Code Type: arm64 (Native)
Parent Process: debugserver [559]
Date/Time: 2014-01-18 01:42:15.082 +0800
OS Version: iOS 7.0.4 (11B554a)
Report Version: 104
Thread 0:
0 libsystem_kernel.dylib 0x000000018ffa173c __chmod + 8
1 libsystem_kernel.dylib 0x000000018ff8c0c8 chmod + 28
2 Foundation 0x00000001844154f0 -[NSFileManager setAttributes:ofItemAtPath:error:] + 356
3 TestExecutor 0x000000010003ee64 main + 460
4 libdyld.dylib 0x000000018fea7aa0 start + 4
Binary Images:
0x100038000 - 0x10003ffff TestExecutor arm64 <6363d76973ce3fda891b623df5eb63b3> /var/mobile/Applications/17A07293-0E73-4D67-BF0E-AB5E806C8960/TestExecutor.app/TestExecutor
0x1843c0000 - 0x1845ffffb Foundation arm64 <b899c77034783549a78bf3a52730f20f> /System/Library/Frameworks/Foundation.framework/Foundation
0x18fea4000 - 0x18fea7fff libdyld.dylib arm64 <315864e397783fed95e9a5c1654c5e80> /usr/lib/system/libdyld.dylib
0x18ff88000 - 0x18ffa7ffd libsystem_kernel.dylib arm64 <62e992db941432b19fb88aef8a3cf46c> /usr/lib/system/libsystem_kernel.dylib

Related

App Crash: NSInvalidArgumentException

[__NSArrayM relatedObjectDidChange]: unrecognized selector sent to instance
error Class: NSInvalidArgumentException
the crash report stackTrace:
0 CoreFoundation 0x33d153e7 <redacted> + 162
1 libobjc.A.dylib 0x3ba06963 objc_exception_throw + 30
2 CoreFoundation 0x33d18f31 <redacted> + 0
3 CoreFoundation 0x33d1764d <redacted> + 392
4 CoreFoundation 0x33c6f208 _CF_forwarding_prep_0 + 24
5 EventKit 0x3440af03 <redacted> + 30
6 EventKit 0x34410225 <redacted> + 396
7 EventKit 0x34410095 <redacted> + 28
8 EventKit 0x3440d3fd <redacted> + 396
9 Calendar 0x000f10a5 -[createNewEventView editEvent:] + 1696
10 UIKit 0x35c0f087 <redacted> + 70
11 UIKit 0x35c0f111 <redacted> + 120
12 UIKit 0x35c0f087 <redacted> + 70
13 UIKit 0x35c0f03b <redacted> + 30
14 UIKit 0x35c0f015 <redacted> + 44
15 UIKit 0x35c0e8cb <redacted> + 502
16 UIKit 0x35c0edb9 <redacted> + 488
17 UIKit 0x35b375f9 <redacted> + 524
18 UIKit 0x35b248e1 <redacted> + 380
19 UIKit 0x35b241ef <redacted> + 6198
20 GraphicsServices 0x3783b5f7 <redacted> + 590
21 GraphicsServices 0x3783b227 <redacted> + 34
22 CoreFoundation 0x33cea3e7 <redacted> + 34
23 CoreFoundation 0x33cea38b <redacted> + 138
24 CoreFoundation 0x33ce920f <redacted> + 1382
25 CoreFoundation 0x33c5c23d CFRunLoopRunSpecific + 356
26 CoreFoundation 0x33c5c0c9 CFRunLoopRunInMode + 104
27 GraphicsServices 0x3783a33b GSEventRunModal + 74
28 UIKit 0x35b782b9 UIApplicationMain + 1120
29 Calendar 0x000a9bbf main + 66
30 Calendar 0x0003a600 start + 40
What does such error means, and what is the possibilities for such error?
My implementation of editEvent method:
-(void) editEvent:(EKSpan )span
{
EKEvent * newEditingEvent = self.EventToEdit;
CalendarAppDataObject* theDataObject = [self theAppDataObject];
if(eventCalendar != nil && theDataObject.selectedCalendarsForDisplayData != nil){
NSArray *arrayDataUnarchiver =(NSArray *) [NSKeyedUnarchiver unarchiveObjectWithData:theDataObject.selectedCalendarsForDisplayData];
NSMutableSet * uniqueId = [[NSMutableSet alloc ] initWithArray:arrayDataUnarchiver];
[uniqueId addObject:eventCalendar.calendarIdentifier];
NSArray * selectedCal = [uniqueId allObjects];
NSData *arrayDataArchiver = [NSKeyedArchiver archivedDataWithRootObject:selectedCal];
theDataObject.selectedCalendarsForDisplayData = arrayDataArchiver;
//save selected to database
NSError *error;
self.managedObjectContext = theDataObject.managedObjectContext;
NSManagedObjectContext *context = [self managedObjectContext];
// **** log objects currently in database ****
// create fetch object, this objects fetch's the objects out of the database
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Settings" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects= [context executeFetchRequest:fetchRequest error:&error] ;
for (NSManagedObject *info in fetchedObjects)
{
[info setValue:arrayDataArchiver forKey:#"selectedCalendarsForDisplayData"] ;
}
//this is for comitting changes to core data
[context save:&error];
[fetchRequest release];
[uniqueId release];
}
NSString * eventNotesString = #"";
if(self.eventNotes != nil)
{
eventNotesString = self.eventNotes;
}
newEditingEvent.notes = [EventsDataUtil generateEventsNoteForSavingColor:eventNotesString colorToSave:self.eventBackColor];
if(self.eventRecurrenceRule != nil)
{
NSArray * RecRulesArray = [[[NSArray alloc ] initWithObjects:self.eventRecurrenceRule, nil]autorelease];
if(theDataObject.isRepeatChanged)
{
[newEditingEvent setRecurrenceRules:RecRulesArray];
}
}else
{
[newEditingEvent setRecurrenceRules:nil];
}
if([[ self.eventTitle stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] isEqualToString:#""])
{
self.eventTitle = #"New Event";
}
newEditingEvent.title = self.eventTitle;
if(isLocationPhoneNumber)
{
NSString * PhoneLocationString = #"tel:";
PhoneLocationString = [PhoneLocationString stringByAppendingFormat:#"%#", [self.contactPhoneNumber stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
newEditingEvent.location = PhoneLocationString;
}
else
{
newEditingEvent.location = self.eventLocation;
}
newEditingEvent.startDate = self.eventStartDate;
newEditingEvent.endDate =self.eventEndDate;
newEditingEvent.allDay = self.eventAllDay;
newEditingEvent.calendar = self.eventCalendar;
newEditingEvent.URL = self.eventURL;
// repeat and alert
NSArray * Alarms = nil;
if(self.eventAlert !=nil)
{
if(self.eventSecondAlert !=nil)
{
Alarms = [[[NSArray alloc] initWithObjects:self.eventAlert,self.eventSecondAlert, nil]autorelease];
}
else {
Alarms = [[[NSArray alloc] initWithObjects:self.eventAlert, nil]autorelease];
}
}
newEditingEvent.alarms = Alarms;
NSError *err;
[newEditingEvent setCalendar:self.eventCalendar];
[sharedEventStore saveEvent:newEditingEvent span:span commit:YES error:&err];
theDataObject.needUpdate = YES;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
[[NSNotificationCenter defaultCenter] postNotificationName:#"dismissEventDetails" object:nil];
}
else{
[self dismissViewControllerAnimated:YES completion:NULL];
}
}
The error report tells you everything you need to know:
[__NSArrayM relatedObjectDidChange]: unrecognized selector sent to instance
Which means that the NSArray class does not have a method called relatedObjectDidChange, so your code obviously calls this somewhere:
[someArray relatedObjectDidChange];
Without seeing your code, I cannot provide more help. I'd like to see this method:
[createNewEventView editEvent:]
and the definition of that class
The method relatedObjectDidChange is sent to an object of class NSArray which the class does not respond to. Did you mix up an NSMutableArray with an NSArray somewhere?
Or is relatedObjectDidChange a method that you did implement yourself on one of your objects? In that case you probably assigned an NSArray to a variable of which you expect to be of your very own class.

iPhone app crashes on device but not on simulator

I am having trouble with an application. It runs in the simulator, but when I try to run it on a device, it crashes.
I tested it and it worked before submitting it to Apple for the review, but now, when I tried to take another look at it, it keeps crashing. Also, it doesn't crash right at the start, but when I try to navigate to a second view. Please let me know if you can help me to figure it out. Thanks!
(I have already tried setting NSZombieEnable, as I found this suggestion/answer in different posts but it does not work for me)
OS Version: iPhone OS 5.1.1 (9B206)
Report Version: 104
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x6f466874
Crashed Thread: 0
Thread 0 name: Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0 libobjc.A.dylib 0x335b2f7e objc_msgSend + 22
1 Foundation 0x34d24d04 _NSDescriptionWithLocaleFunc + 44
2 CoreFoundation 0x3597496e __CFStringAppendFormatCore + 7998
3 CoreFoundation 0x358ef1d8 _CFStringCreateWithFormatAndArgumentsAux + 68
4 Foundation 0x34d24c2e +[NSString stringWithFormat:] + 54
5 Sustain 0x00082148 +[HTMLParser parseDataForRequest:error:] (HTMLParser.m:169)
6 Sustain 0x00085a5a -[ProxyRequestResponseHandler requestFinished:] (ProxyRequestResponseHandler.m:251)
7 CoreFoundation 0x358f31f4 -[NSObject performSelector:withObject:] + 36
8 Sustain 0x00054364 -[ASIHTTPRequest reportFinished] (ASIHTTPRequest.m:2004)
9 CoreFoundation 0x358f31f4 -[NSObject performSelector:withObject:] + 36
10 Foundation 0x34dc3740 __NSThreadPerformPerform + 344
11 CoreFoundation 0x35968acc __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 8
12 CoreFoundation 0x35968298 __CFRunLoopDoSources0 + 208
13 CoreFoundation 0x3596703e __CFRunLoopRun + 646
14 CoreFoundation 0x358ea49e CFRunLoopRunSpecific + 294
15 CoreFoundation 0x358ea366 CFRunLoopRunInMode + 98
16 GraphicsServices 0x33685432 GSEventRunModal + 130
17 UIKit 0x330c2cce UIApplicationMain + 1074
18 Sustain 0x00019c26 main (main.m:16)
19 Sustain 0x00019bc0 start + 32
Thread 0 crashed with ARM Thread State:
r0: 0x00128a98 r1: 0x325894f6 r2: 0x359eccd5 r3: 0x6f46687c
r4: 0x32588417 r5: 0x00000000 r6: 0x3f3078c8 r7: 0x2fe0cb70
r8: 0x2fe0cc13 r9: 0x0c96253d r10: 0x359730b6 r11: 0x00000000
ip: 0x3f2e26f0 sp: 0x2fe0cb5c lr: 0x34d24d0b pc: 0x335b2f7e
cpsr: 0x200f0030
Here is the mathod you requested in HTMLParser
+ (BOOL)parseDataForRequest:(ASIHTTPRequest *)request error:(NSError **)error
{
NSStringEncoding encoding = [request responseEncoding];
NSString *string = [[NSString alloc] initWithContentsOfFile:[request downloadDestinationPath] usedEncoding:&encoding error:NULL];
[string release];
NSURL *baseURL = [request url];
xmlInitParser();
xmlDocPtr doc;
if ([request downloadDestinationPath]) {
doc = htmlReadFile([[request downloadDestinationPath] cStringUsingEncoding:NSUTF8StringEncoding], [self encodingNameForStringEncoding:encoding], HTML_PARSE_RECOVER | HTML_PARSE_NONET | HTML_PARSE_NOWARNING | HTML_PARSE_NOERROR);
} else {
NSData *data = [request responseData];
doc = htmlReadMemory([data bytes], (int)[data length], "", [self encodingNameForStringEncoding:encoding], HTML_PARSE_RECOVER | HTML_PARSE_NONET | HTML_PARSE_NOWARNING | HTML_PARSE_NOERROR);
}
if (doc == NULL) {
[super parseDataForRequest:request error:error];
return YES;
}
// Create xpath evaluation context
xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc);
if(xpathCtx == NULL) {
if (error) {
*error = [NSError errorWithDomain:NetworkRequestErrorDomain code:101 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:#"Error: unable to create new XPath context",NSLocalizedDescriptionKey,nil]];
}
return NO;
}
// Evaluate xpath expression
xmlXPathObjectPtr xpathObj = xmlXPathEvalExpression(xpathExpr, xpathCtx);
if(xpathObj == NULL) {
xmlXPathFreeContext(xpathCtx);
if (error) {
*error = [NSError errorWithDomain:NetworkRequestErrorDomain code:101 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:#"Error: unable to evaluate XPath expression!",NSLocalizedDescriptionKey,nil]];
}
return NO;
}
// Now loop through our matches
xmlNodeSetPtr nodes = xpathObj->nodesetval;
int size = (nodes) ? nodes->nodeNr : 0;
int i;
for(i = size - 1; i >= 0; i--) {
assert(nodes->nodeTab[i]);
NSString *parentName = [NSString stringWithCString:(char *)nodes->nodeTab[i]->parent->name encoding:encoding];
NSString *nodeName = [NSString stringWithCString:(char *)nodes->nodeTab[i]->name encoding:encoding];
xmlChar *nodeValue = xmlNodeGetContent(nodes->nodeTab[i]);
NSString *value = [NSString stringWithCString:(char *)nodeValue encoding:encoding];
xmlFree(nodeValue);
// Here we add a <base> element to the header to make the end result play better with javascript
// (UIWebView seemed to ignore the Content-Base http header when I tried)
if ([[nodeName lowercaseString] isEqualToString:#"head"]) {
xmlNodePtr node = xmlNewNode(NULL, (xmlChar *)"base");
xmlNewProp(node, (xmlChar *)"href", (xmlChar *)[[baseURL absoluteString] cStringUsingEncoding:encoding]);
node = xmlDocCopyNode(node, doc, 1);
xmlAddChild(nodes->nodeTab[i], node);
// Our xpath query matched all <link> elements, but we're only interested in stylesheets
// We do the work here rather than in the xPath query because the query is case-sensitive, and we want to match on 'stylesheet', 'StyleSHEEt' etc
} else if ([[parentName lowercaseString] isEqualToString:#"link"]) {
xmlChar *relAttribute = xmlGetNoNsProp(nodes->nodeTab[i]->parent,(xmlChar *)"rel");
if (relAttribute) {
NSString *rel = [NSString stringWithCString:(char *)relAttribute encoding:encoding];
xmlFree(relAttribute);
if ([[rel lowercaseString] isEqualToString:#"stylesheet"] || [[rel lowercaseString] isEqualToString:#"alternate stylesheet"]) {
xmlNodeSetContent(nodes->nodeTab[i], (xmlChar *)[[self localURLForURL:value withBaseURL:baseURL] cStringUsingEncoding:encoding]);
}
}
// Parse the content of <style> tags and style attributes to find external image urls or external css files
} else if ([[nodeName lowercaseString] isEqualToString:#"style"]) {
xmlNodeSetContent(nodes->nodeTab[i], (xmlChar *)[[CSSParser replaceURLsInCSSString:value withBaseURL:baseURL] cStringUsingEncoding:encoding]);
// Parse the content of <source src=""> tags (HTML 5 audio + video)
// We explictly disable the download of files with .webm, .ogv and .ogg extensions, since it's highly likely they won't be useful to us
} else if ([[parentName lowercaseString] isEqualToString:#"source"] || [[parentName lowercaseString] isEqualToString:#"audio"]) {
NSString *fileExtension = [[value pathExtension] lowercaseString];
if (![fileExtension isEqualToString:#"ogg"] && ![fileExtension isEqualToString:#"ogv"] && ![fileExtension isEqualToString:#"webm"]) {
xmlNodeSetContent(nodes->nodeTab[i], (xmlChar *)[[self localURLForURL:value withBaseURL:baseURL] cStringUsingEncoding:encoding]);
}
// For all other elements matched by our xpath query (except hyperlinks), add the content as an external url to fetch
} else if (![[parentName lowercaseString] isEqualToString:#"a"]) {
xmlNodeSetContent(nodes->nodeTab[i], (xmlChar *)[[self localURLForURL:value withBaseURL:baseURL] cStringUsingEncoding:encoding]);
}
if (nodes->nodeTab[i]->type != XML_NAMESPACE_DECL) {
nodes->nodeTab[i] = NULL;
}
}
xmlXPathFreeObject(xpathObj);
xmlXPathFreeContext(xpathCtx);
// We'll use the xmlsave API so we can strip the xml declaration
xmlSaveCtxtPtr saveContext;
if ([request downloadDestinationPath]) {
// Truncate the file first
NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease];
[fileManager createFileAtPath:[request downloadDestinationPath] contents:nil attributes:nil];
saveContext = xmlSaveToFd([[NSFileHandle fileHandleForWritingAtPath:[request downloadDestinationPath]] fileDescriptor],[self encodingNameForStringEncoding:NSUTF8StringEncoding],2|8); // 2 == XML_SAVE_NO_DECL, this isn't declared on Mac OS 10.5
xmlSaveDoc(saveContext, doc);
xmlSaveClose(saveContext);
} else {
#if TARGET_OS_MAC && MAC_OS_X_VERSION_MAX_ALLOWED <= __MAC_10_5
// xmlSaveToBuffer() is not implemented in the 10.5 version of libxml
NSString *tempPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]];
[[[[NSFileManager alloc] init] autorelease] createFileAtPath:tempPath contents:nil attributes:nil];
saveContext = xmlSaveToFd([[NSFileHandle fileHandleForWritingAtPath:tempPath] fileDescriptor],[self encodingNameForStringEncoding:NSUTF8StringEncoding],2|8); // 2 == XML_SAVE_NO_DECL, this isn't declared on Mac OS 10.5
xmlSaveDoc(saveContext, doc);
xmlSaveClose(saveContext);
[request setRawResponseData:[NSMutableData dataWithContentsOfFile:tempPath]];
#else
xmlBufferPtr buffer = xmlBufferCreate();
saveContext = xmlSaveToBuffer(buffer,[self encodingNameForStringEncoding:NSUTF8StringEncoding],2|8); // 2 == XML_SAVE_NO_DECL, this isn't declared on Mac OS 10.5
xmlSaveDoc(saveContext, doc);
xmlSaveClose(saveContext);
[request setRawResponseData:[[[NSMutableData alloc] initWithBytes:buffer->content length:buffer->use] autorelease]];
xmlBufferFree(buffer);
#endif
}
NSString *contentType = [[[request responseHeaders] objectForKey:#"Content-Type"] lowercaseString];
contentType = [[contentType componentsSeparatedByString:#";"] objectAtIndex:0];
if (!contentType) {
contentType = #"text/html";
}
[[request responseHeaders] setValue:[NSString stringWithFormat:#"%#; charset=utf-8"] forKey:#"Content-Type"];
[request setResponseEncoding:NSUTF8StringEncoding];
xmlFreeDoc(doc);
doc = nil;
[super parseDataForRequest:request error:error];
return YES;
}
In the second view I load a webView that gets cached after being loaded.
I used this project in order to obtain this:
https://github.com/pokeb/ProxyingUIWebView
What's weird is that it used to work, but now it doesn't anymore.
I have tried to test it on another device and I get the same crash.
This is what I have in my secondarry view controller:
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSString *urlString = [NSString stringWithFormat:#"%#", request.URL];
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *baseUrl = [mainBundle objectForInfoDictionaryKey:#"testUrl"];
if ([urlString rangeOfString:baseUrl].location != NSNotFound) //Check if URL is in-app.
{
NSURLRequest *testRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://127.0.0.1:8080/?url=http.somelink.net"]];
NSString *requestUrlString = [NSString stringWithFormat:#"%#",request.URL];
NSString *testUrlString = [NSString stringWithFormat:#"%#",testRequest.URL];
if ([requestUrlString isEqualToString:testUrlString]) //First view load
{
return YES;
}
if (navigationType == UIWebViewNavigationTypeLinkClicked ||
navigationType == UIWebViewNavigationTypeFormSubmitted ||
navigationType == UIWebViewNavigationTypeFormResubmitted ||
navigationType == UIWebViewNavigationTypeReload ||
navigationType == UIWebViewNavigationTypeOther)
{
if ([requestUrlString rangeOfString:#"Id="].location != NSNotFound) //Navigate to
{ //secondary view.
SecondaryTopTenSwapsViewController *secondaryController = [[SecondaryTopTenSwapsViewController alloc] init];
secondaryController.urlRequest = request;
[self.navigationController pushViewController:secondaryController animated:YES];
}
return NO;
}
return YES;
}
else //Not in-app URL. Check if user wants to leave application and open Safari.
{
UIAlertView *leaveApplicationAlert = [[UIAlertView alloc] initWithTitle:#"Open link?" message:#"Are you sure you want to exit the application and open the link in Safari?" delegate:self cancelButtonTitle:#"NO" otherButtonTitles:#"YES", nil];
leaveApplicationAlert.tag = 1;
[leaveApplicationAlert show];
externalUrl = request.URL;
return NO;
}
}
Also, I found that in my secondary view controller it crashes right after
-(void)webViewDidStartLoad:(UIWebView *)webView
Also, it can't be a memory issue, as if I receive a memory warning, I pop to the root view controller and release all the subviews.
You are trying to access an object by casting it's format type incorrectly.
For example, you are trying to access an integer value by using the format type %# rather than %i or %d.
NSInteger someInteger = 255;
NSString *string = [NSString stringWithFormat:#"Hello, my favourite number is %#", someInteger"];
If you post some code, I can outline where this is occurring.
From your stack trace, it looks like the string where the issue is arising is being passed into a method where the HTMLParser object is the receiver.
Edit---
Another possibility is that one of the arguments passed to the NSString has already been released and cannot be accessed as it has been deallocated and furthermore removed from memory.
Edit----
I believe that the problem is on this line:
[[request responseHeaders] setValue:[NSString stringWithFormat:#"%#; charset=utf-8"] forKey:#"Content-Type"];
You use the format string %#, yet do not provide an NSString as an argument.
I believe that you meant to code the following:
[[request responseHeaders] setValue:[NSString stringWithFormat:#"%#; charset=utf-8", contentType] forKey:#"Content-Type"];
Turn on Zombies and Malloc Scribble (scheme diagnostics) and debug your app (either simulator or device or both). Likely you have a deallocated object you are working with. Random memory accesses may succeed or fail when you read (or write) via a deallocated object or pointer. That's the most common reason for such inconsistent behavior.

UIImageWriteToSavedPhotosAlbum crash stack trace / error log: What is the crash?

Can someone tell me what type of crash this is? (i.e. Out of memory?)
I received this crash log but I have no idea what the problem is.
Could I wrap the code in a try catch block and at least handle this gracefully.
I don't have any steps from a user and I can't get my iOS device to crash in this code.
Thread 0 name: Dispatch queue: com.apple.assetsd.sharedPersistentStoreCoordinator
Thread 0 Crashed:
0 libsystem_kernel.dylib 0x3339f32c __pthread_kill + 8
1 libsystem_c.dylib 0x376e7f54 pthread_kill
2 libsystem_c.dylib 0x376e0fe4 abort
3 libc++abi.dylib 0x33384f64 abort_message + 40
4 libc++abi.dylib 0x33382346 _ZL17default_terminatev + 18
5 libobjc.A.dylib 0x332b72dc _objc_terminate
6 libc++abi.dylib 0x333823be _ZL19safe_handler_callerPFvvE + 70
7 libc++abi.dylib 0x33382372 __cxxabiv1::__terminate(void (*)()) + 2
8 libc++abi.dylib 0x33382882 __cxa_call_terminate + 46
9 libc++abi.dylib 0x333832ac __gxx_personality_sj0 + 968
10 libunwind.dylib 0x33170a7e unwind_phase2 + 66
11 libunwind.dylib 0x33170c0e _Unwind_SjLj_Resume + 122
12 PhotoLibraryServices 0x324d99ea -[PLPhotoLibrary(Protected) loadDatabase]
13 PhotoLibraryServices 0x324a217e -[PLPhotoLibrary initWithPath:canTriggerDatabaseUpdate:]
14 PhotoLibraryServices 0x324e919e __42+[PLSharedPhotoLibrary sharedPhotoLibrary]_block_invoke_0
15 libdispatch.dylib 0x347c5570 dispatch_once_f$VARIANT$up
16 PhotoLibraryServices 0x324e915c +[PLSharedPhotoLibrary sharedPhotoLibrary]
17 PhotoLibraryServices 0x324aa068 __withSavedPhotosAlbumUUID_block_invoke_0
18 libdispatch.dylib 0x347c5570 dispatch_once_f$VARIANT$up
19 PhotoLibraryServices 0x324a9430 withSavedPhotosAlbumUUID
20 PhotoLibraryServices 0x324a9372 PLSaveImageToCameraRoll
21 UIKit 0x30b9f1ce UIImageWriteToSavedPhotosAlbum
Here is the code:
- (void) imagePickerController: (UIImagePickerController *) picker didFinishPickingMediaWithInfo: (NSDictionary *) info {
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
UIImage *originalImage, *editedImage, *imageToSave;
// Handle a still image capture
if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0)
== kCFCompareEqualTo) {
editedImage = (UIImage *) [info objectForKey:
UIImagePickerControllerEditedImage];
originalImage = (UIImage *) [info objectForKey:
UIImagePickerControllerOriginalImage];
if (editedImage) {
imageToSave = editedImage;
} else {
imageToSave = originalImage;
}
if (imagePickerSourceType == UIImagePickerControllerSourceTypeCamera) {
// Save the new image (original or edited) to the Camera Roll
UIImageWriteToSavedPhotosAlbum (imageToSave, nil, nil , nil);
}
}
UIImageWriteToSavedPhotosAlbum (imageToSave, nil, nil , nil);
I cannot get it to crash on my device or I would have a better chance of figuring this out. This is a crash log from iTunes Connect.

-[NSFileManager removeItemAtPath:error:] makes app CRASH

We are getting an error when trying to delete a folder on startup. We are removing a folder placed in documents used to store cache-data. Any idea why it is crashing?
0 libsystem_kernel.dylib 0x364b62d0 __unlink + 8
1 libsystem_kernel.dylib 0x364b46a6 unlink + 2
2 libremovefile.dylib 0x313099c8 __removefile_process_file + 232
3 libremovefile.dylib 0x31309a50 __removefile_tree_walker + 100
4 libremovefile.dylib 0x313090f4 removefile + 88
5 Foundation 0x3156c11a -[NSFilesystemItemRemoveOperation main] + 138
6 Foundation 0x31551d14 -[__NSOperationInternal start] + 652
7 Foundation 0x31551a78 -[NSOperation start] + 16
8 Foundation 0x3156bfda -[NSFileManager removeItemAtPath:error:] + 46
9 VG 0x0004f030 +[VGFileManager removeOldCacheFolder] + 319536
10 VG 0x00003e1c -[VGAppDelegate application:didFinishLaunchingWithOptions:] + 11804
11 UIKit 0x31de481a -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 766
12 UIKit 0x31ddeb5e -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 266
13 UIKit 0x31db37d0 -[UIApplication handleEvent:withNewEvent:] + 1108
14 UIKit 0x31db320e -[UIApplication sendEvent:] + 38
15 UIKit 0x31db2c4c _UIApplicationHandleEvent + 5084
16 GraphicsServices 0x34720e70 PurpleEventCallback + 660
17 CoreFoundation 0x30ba5a90 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 20
18 CoreFoundation 0x30ba7838 __CFRunLoopDoSource1 + 160
19 CoreFoundation 0x30ba8606 __CFRunLoopRun + 514
20 CoreFoundation 0x30b38ebc CFRunLoopRunSpecific + 224
21 CoreFoundation 0x30b38dc4 CFRunLoopRunInMode + 52
22 UIKit 0x31dddd42 -[UIApplication _run] + 366
23 UIKit 0x31ddb800 UIApplicationMain + 664
24 VG 0x0000bd96 0x1000 + 44438
25 VG 0x00003990 0x1000 + 10640
This is the function called on "9".
+ (void)removeOldCacheFolder {
BOOL oldCacheFolderRemoved = [[NSUserDefaults standardUserDefaults] boolForKey:kVGFileCacheFolder_1_2];
if(!oldCacheFolderRemoved){
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; //Get documents folder
NSString *cacheDirectory = [documentsDirectory stringByAppendingPathComponent:kVGFileCacheFolder_1_2];
if ([[NSFileManager defaultManager] fileExistsAtPath:cacheDirectory]) {
NSError *error = nil;
if (!([[NSFileManager defaultManager] removeItemAtPath:cacheDirectory error:&error])) {
ELog(#"Unresolved error %#, %#", error, [error userInfo]);
}
else{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:kVGFileCacheFolder_1_2];
}
}
}
BOOL oldSQLFileDeleted = [[NSUserDefaults standardUserDefaults] boolForKey:kVGFileDb_1_3];
if(!oldSQLFileDeleted){
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; //Get documents folder
NSString *sqlFile = [documentsDirectory stringByAppendingPathComponent:kVGFileDb_1_3];
if ([[NSFileManager defaultManager] fileExistsAtPath:sqlFile]) {
NSError *error = nil;
if (!([[NSFileManager defaultManager] removeItemAtPath:sqlFile error:&error])) {
ELog(#"Unresolved error %#, %#", error, [error userInfo]);
}
else{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:kVGFileDb_1_3];
}
}
}
}
EDIT: Just discovered this process can take 2 minutes...
Maybe we're getting killed by the iOS watchdog, any app that takes too long to launch gets terminated. Could it be a too time consuming process?
There is a special caches folder that iOS maintains - it's contents is not backed up whereas you data will be backed up when syncing.
NSString *tmpDir = NSTemporaryDirectory();
You trimmed of the exception type from you dump. You could perhaps learn something about the crash from the exception type and code.
I read through the version 1.2 section of the code and honestly it looks just fine. Check your define for kVGFileCacheFolder_1_2 - I assume something like #"file.dat" which is also fine.
Check that the file is closed and there is no other ongoing operations on the file.

App crashing when adding to Core Data

Does anyone can tell me what is the source of this crash, because I have no idea what could be wrong. Here the crash log:
Incident Identifier: 517593EA-7CBC-4790-A924-966938AAA01B
CrashReporter Key: 179f2e12142cea96d45f2f6475c7f89a7a702d90
Hardware Model: iPhone1,2
Process: AppName [3579]
Path: /var/mobile/Applications/9FBBBD37-2A31-4240-A8AC-64E5BD0B00C0/AppName.app/AppName
Identifier: AppName
Version: ??? (???)
Code Type: ARM (Native)
Parent Process: launchd [1]
Date/Time: 2011-04-04 15:51:32.466 +0200
OS Version: iPhone OS 4.2.1 (8C148)
Report Version: 104
Exception Type: EXC_BAD_ACCESS (SIGBUS)
Exception Codes: KERN_PROTECTION_FAILURE at 0x00000004
Crashed Thread: 9
Thread 0:
0 libSystem.B.dylib 0x35d5b3b0 mach_msg_trap + 20
1 libSystem.B.dylib 0x35d5d894 mach_msg + 60
2 CoreFoundation 0x37521f7c __CFRunLoopServiceMachPort + 88
3 CoreFoundation 0x37521780 __CFRunLoopRun + 400
4 CoreFoundation 0x37521504 CFRunLoopRunSpecific + 220
5 CoreFoundation 0x37521412 CFRunLoopRunInMode + 54
6 GraphicsServices 0x33e76d1c GSEventRunModal + 188
7 UIKit 0x3591d574 -[UIApplication _run] + 580
8 UIKit 0x3591a550 UIApplicationMain + 964
9 AppName 0x00002c9a main (main.m:13)
10 AppName 0x00002c64 start + 32
Thread 1:
0 libSystem.B.dylib 0x35d8f974 kevent + 24
1 libSystem.B.dylib 0x35e5e2fc _dispatch_mgr_invoke + 88
2 libSystem.B.dylib 0x35e5dd68 _dispatch_queue_invoke + 96
3 libSystem.B.dylib 0x35e5d788 _dispatch_worker_thread2 + 120
4 libSystem.B.dylib 0x35de6970 _pthread_wqthread + 392
5 libSystem.B.dylib 0x35ddd2fc start_wqthread + 0
Thread 2:
0 libSystem.B.dylib 0x35d5b3b0 mach_msg_trap + 20
1 libSystem.B.dylib 0x35d5d894 mach_msg + 60
2 CoreFoundation 0x37521f7c __CFRunLoopServiceMachPort + 88
3 CoreFoundation 0x37521780 __CFRunLoopRun + 400
4 CoreFoundation 0x37521504 CFRunLoopRunSpecific + 220
5 CoreFoundation 0x37521412 CFRunLoopRunInMode + 54
6 WebCore 0x3318bd14 RunWebThread(void*) + 524
7 libSystem.B.dylib 0x35de5b44 _pthread_start + 364
8 libSystem.B.dylib 0x35dd77a4 thread_start + 0
Thread 3:
0 libSystem.B.dylib 0x35de454c __semwait_signal + 24
1 libSystem.B.dylib 0x35d5d198 nanosleep + 120
2 Foundation 0x351e066a +[NSThread sleepForTimeInterval:] + 98
3 AppName 0x00005b40 -[Syncer requestPump] (Syncer.m:116)
4 Foundation 0x3515cb8a -[NSThread main] + 42
5 Foundation 0x35155b90 __NSThread__main__ + 908
6 libSystem.B.dylib 0x35de5b44 _pthread_start + 364
7 libSystem.B.dylib 0x35dd77a4 thread_start + 0
Thread 4:
0 libSystem.B.dylib 0x35d5b3b0 mach_msg_trap + 20
1 libSystem.B.dylib 0x35d5d894 mach_msg + 60
2 CoreFoundation 0x37521f7c __CFRunLoopServiceMachPort + 88
3 CoreFoundation 0x37521780 __CFRunLoopRun + 400
4 CoreFoundation 0x37521504 CFRunLoopRunSpecific + 220
5 CoreFoundation 0x37521412 CFRunLoopRunInMode + 54
6 Foundation 0x3517ec4e +[NSURLConnection(NSURLConnectionReallyInternal) _resourceLoadLoop:] + 210
7 Foundation 0x3515cb8a -[NSThread main] + 42
8 Foundation 0x35155b90 __NSThread__main__ + 908
9 libSystem.B.dylib 0x35de5b44 _pthread_start + 364
10 libSystem.B.dylib 0x35dd77a4 thread_start + 0
Thread 5:
0 libSystem.B.dylib 0x35d848d8 select$DARWIN_EXTSN + 20
1 CoreFoundation 0x3755aa34 __CFSocketManager + 356
2 libSystem.B.dylib 0x35de5b44 _pthread_start + 364
3 libSystem.B.dylib 0x35dd77a4 thread_start + 0
Thread 6:
0 libSystem.B.dylib 0x35de72fc __workq_kernreturn + 8
1 libSystem.B.dylib 0x35de6b50 _pthread_wqthread + 872
2 libSystem.B.dylib 0x35ddd2fc start_wqthread + 0
Thread 7:
0 libSystem.B.dylib 0x35de72fc __workq_kernreturn + 8
1 libSystem.B.dylib 0x35de6b50 _pthread_wqthread + 872
2 libSystem.B.dylib 0x35ddd2fc start_wqthread + 0
Thread 8:
0 libSystem.B.dylib 0x35de72fc __workq_kernreturn + 8
1 libSystem.B.dylib 0x35de6b50 _pthread_wqthread + 872
2 libSystem.B.dylib 0x35ddd2fc start_wqthread + 0
Thread 9 Crashed:
0 CoreFoundation 0x374fec60 __CFBasicHashAddValue + 140
1 CoreFoundation 0x374ff8fc CFBasicHashAddValue + 276
2 CoreFoundation 0x3750410a CFSetAddValue + 90
3 CoreFoundation 0x3752be2a -[__NSCFSet addObject:] + 34
4 CoreData 0x34998002 -[NSManagedObjectContext(_NSInternalAdditions) _insertObjectWithGlobalID:globalID:] + 134
5 CoreData 0x34997ec6 -[NSManagedObjectContext insertObject:] + 58
6 CoreData 0x34979cbc -[NSManagedObject initWithEntity:insertIntoManagedObjectContext:] + 248
7 AppName 0x00066512 -[SNServerChanges newItemWithJSONStringFor:withList:] (SNServerChanges.m:655)
8 AppName 0x0006847a -[SNServerChanges requestDidFinishThread:] (SNServerChanges.m:282)
9 AppName 0x00065b28 -[SNServerChanges makeChanges:] (SNServerChanges.m:41)
10 Foundation 0x3515cb8a -[NSThread main] + 42
11 Foundation 0x35155b90 __NSThread__main__ + 908
12 libSystem.B.dylib 0x35de5b44 _pthread_start + 364
13 libSystem.B.dylib 0x35dd77a4 thread_start + 0
Thread 9 crashed with ARM Thread State:
r0: 0x0405ceb0 r1: 0x00000000 r2: 0x00000004 r3: 0x00000001
r4: 0x0405ceb0 r5: 0x002e1c20 r6: 0x00000004 r7: 0x04468884
r8: 0x00000001 r9: 0x044688ac r10: 0x0405ceb0 r11: 0x002bf670
ip: 0x00000000 sp: 0x04468870 lr: 0x34982145 pc: 0x374fec60
cpsr: 0x20000010
One thing I know is the fact that there is something wrong when I try to add new object to Core Data.
This is how I set up Core Data:
- (id) init {
if (self = [super init]) {
NSString* path = [[NSBundle mainBundle] pathForResource:#"Main210" ofType:#"mom"];
NSURL* url = [NSURL fileURLWithPath:path];
url = [[NSURL alloc] initFileURLWithPath:path];
managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:url];
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, nil];
NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: #"data.bin"]];
NSError *error = nil;
sqlite3_enable_shared_cache(0); // from apple Bug ID# 8055992
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error])
{
NSLog(#"Error: %# \n\n userInfo: %# \n\n ", error, [error userInfo]);
NSError *underlyingError = [[error userInfo] objectForKey:NSUnderlyingErrorKey];
if (underlyingError) {
NSLog(#"Underlying error: %# \n\n userInfo: %# \n\n", underlyingError, [underlyingError userInfo]);
}
NSArray *detailedErrors = [[error userInfo] objectForKey:NSDetailedErrorsKey];
for (NSError *detailError in detailedErrors) {
NSLog(#"Detailed error: %# \n\n userInfo: %# \n\n", detailError, [detailError userInfo]);
}
abort();
}
if (persistentStoreCoordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator: persistentStoreCoordinator];
NSUndoManager *undoManager = [[NSUndoManager alloc] init];
[managedObjectContext setUndoManager:undoManager];
[managedObjectContext setMergePolicy:NSMergeByPropertyObjectTrumpMergePolicy];
}
}
return self;
}
And the function which causes crash:
-(void) newItemWithJSONStringFor:(NSArray*) itemsArray withList:(Lista*) lista {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSNumber *databaseID;
if(LOG==1)NSLog(#"Lista : %#, itemsArrayCount: %d",[lista name], [itemsArray count]);
for (int i=0; i<itemsArray.count; i++) {
[NSThread sleepForTimeInterval:EACHITEMWAITTIME];
NSDictionary* jsonItem = [itemsArray objectAtIndex:i];
databaseID = [jsonItem valueForKey:#"Id"];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Item" inManagedObjectContext:[CoreDataHandler syncContext]];
[request setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"databaseID == %qi", [databaseID longLongValue]];
[request setPredicate:predicate];
NSError* error;
NSMutableArray *mutableFetchResults = [[[CoreDataHandler syncContext] executeFetchRequest:request error:&error] mutableCopy];
[request release];
BOOL flag = YES; //will item be created?
if (! (mutableFetchResults && [mutableFetchResults count] == 0) ) {
flag = NO;
}
Item* item = [mutableFetchResults lastObject];
if (!item) {
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Item" inManagedObjectContext:[CoreDataHandler syncContext]];
item = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:[CoreDataHandler syncContext]];
item.databaseID = databaseID;
item.databaseIDSet = [NSNumber numberWithBool:YES];
item.lista = lista;
[mutableFetchResults addObject:item];
}
else {
if(LOG==1)NSLog(#"SNServerChanges - newItemWithJSONString - Modyfing");
}
if(LOG==1)NSLog(#"SNServerChanges - newItemWithJSONString - FillingItem");
// if(LOG==1)NSLog(#"SNServerChanges - newItemWithJSONString - Making new");
//Nazwa
if ([jsonItem valueForKey:#"N"] != [NSNull null])
item.name = [jsonItem valueForKey:#"N"];
//Opis
if ([jsonItem valueForKey:#"D"] != [NSNull null])
item.desc = [jsonItem valueForKey:#"D"];
//Ilosc
if ([jsonItem valueForKey:#"Q"] != [NSNull null])
item.quantity = [jsonItem valueForKey:#"Q"];
//Jednostka
if ([jsonItem valueForKey:#"U"] != [NSNull null])
item.unit = [jsonItem valueForKey:#"U"];
//Checked
if ([jsonItem valueForKey:#"C"] != [NSNull null]){
NSLog(#"SC New : %#, %d",[item fullName], [[item checked] boolValue]);
if(![item.checkedChanged boolValue]){
item.checked = [NSNumber numberWithBool:[[jsonItem valueForKey:#"C"] boolValue]];
}
else
[SyncManager doNextSync];
}
//Pozycja
if ([jsonItem valueForKey:#"O"] != [NSNull null])
item.position = [NSNumber numberWithInt: [[jsonItem valueForKey:#"O"] intValue]];
//Reklama
if([jsonItem valueForKey:#"Adv"]!= nil && [jsonItem valueForKey:#"Adv"]!=[NSNull null]) {
NSDictionary* temp = [jsonItem valueForKey:#"Adv"];
NSString* tempString = [NSString stringWithFormat:#"%#",[temp valueForKey:#"T"]];
item.advert = tempString;
}
//Cena
if ( [jsonItem valueForKey:#"P"] != nil && [jsonItem valueForKey:#"P"]!=[NSNull null])
{
NSObject* obj = [jsonItem valueForKey:#"P"];
item.price=[NSNumber numberWithDouble:[[jsonItem valueForKey:#"P"] doubleValue]];
}
if ([jsonItem valueForKey:#"Pe"] != [NSNull null])
item.priceEstimated = [NSNumber numberWithBool:[[jsonItem valueForKey:#"Pe"] boolValue]];
if ([jsonItem valueForKey:#"Ci"] != [NSNull null])
item.categoryID = [NSNumber numberWithInt: [[jsonItem valueForKey:#"Ci"] intValue]];
if (flag) {
if ( [item.checked boolValue] )
lista.checked = [NSNumber numberWithInt:[lista.checked intValue]+1];
lista.count = [NSNumber numberWithInt:[lista.count intValue]+1];
}
// if(LOG==1)NSLog(#"SNServerChanges - newItemWithJSONString - Fetching");
if(LOG==1)NSLog(#"SNServerChanges - newItemWithJSONString - AddingToItemCache");
if(LOG==1)NSLog(#"\tItem : %#", [item name]);
//[ItemCache processItem: item];
// [(SNServerChanges*)[SNServerChanges sharedInstance] performSelectorOnMainThread:#selector(saveCoreData) withObject:nil waitUntilDone:YES];
if(LOG==1)NSLog(#"SNServerChanges - newItemWithJSONString - ItemAdded");
}
[pool drain];
}
The app is presumably crashing on this line:
item = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:[CoreDataHandler syncContext]];
You have item defined previously as of class Item but now you are assigning a generic NSManagedObject to it. That is probably the cause of the crash.
I can't see where you've gone wrong (unless there's no Item entity in your model - why not NSLog(#"%#",item);?). I've always used a different call to add a new object, instead of the explicit allocation of an NSManagedObject:
[NSEntityDescription insertNewObjectForEntityForName:#"Item"
inManagedObjectContext:managedObjectContext];
Not sure if it matters.