App crashing when adding to Core Data - iphone

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.

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.

objective c - getting null values

I have been stuck on this for some time now but whats happening is that when the request comes back from mysql there is a null value but how do i check that a null value has hit my condition so that i dont store this value in the array. The code is below
The error i keep getting is -[NSNull isEqualToString:]: unrecognized and im trying to bind the array inside a tableview
- (void)viewDidLoad {
JobAddSiteAppDelegate *ja = (JobAddSiteAppDelegate *)[[UIApplication sharedApplication] delegate];
tempArray = [[NSMutableArray alloc] init];
NSString *strURL = [NSString stringWithFormat:#"http://www.bestitjobs.co.uk/appresults3.php", ""];
NSData *nsData = [NSData dataWithContentsOfURL:[NSURL URLWithString: strURL]];
//NSLog(#"JSON: %#", nsData);
//NSString *strResult = [[[NSString alloc] initWithData:nsData encoding:NSUTF8StringEncoding] autorelease];
//NSLog(#"Result: %#",strResult);
//NSError *e = nil;
JSONDecoder* decoder = [[JSONDecoder alloc] init];
NSDictionary* listDictionary = [nsData objectFromJSONData];
NSArray* people =[listDictionary objectForKey:#"jobs"];
for (NSDictionary *person in people) {
NSLog(#"people %#",people);
if([person objectForKey:#"position"] != [NSNull class])
{
NSString *position = [person objectForKey:#"position"];
NSLog(#"position %#",position);
[tempArray addObject: position];
}
}
self.listData = tempArray;
[tempArray release];
[listData release];
[super viewDidLoad];
}
Error
2012-12-06 12:22:11.314 JobAddSite[7718:207] position Senior Network and Systems Consultant
2012-12-06 12:22:11.316 JobAddSite[7718:207] position SAP Business One / SAP B1 Consultant London
2012-12-06 12:22:11.317 JobAddSite[7718:207] position Business Development Manager - Market Leading IT Company
2012-12-06 12:22:11.318 JobAddSite[7718:207] -[NSNull isEqualToString:]: unrecognized selector sent to instance 0xe565e8
2012-12-06 12:22:11.321 JobAddSite[7718:207] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull isEqualToString:]: unrecognized selector sent to instance 0xe565e8'
* Call stack at first throw:
(
0 CoreFoundation 0x00de95a9 exceptionPreprocess + 185
1 libobjc.A.dylib 0x00f3d313 objc_exception_throw + 44
2 CoreFoundation 0x00deb0bb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
3 CoreFoundation 0x00d5a966 __forwarding + 966
4 CoreFoundation 0x00d5a522 _CF_forwarding_prep_0 + 50
5 JobAddSite 0x000024cd -[ResultViewController viewDidLoad] + 604
6 UIKit 0x00389089 -[UIViewController view] + 179
7 UIKit 0x0038aa3d -[UIViewController viewControllerForRotation] + 63
8 UIKit 0x00386988 -[UIViewController _visibleView] + 90
9 UIKit 0x0062893c -[UIClientRotationContext initWithClient:toOrientation:duration:andWindow:] + 354
10 UIKit 0x0030081e -[UIWindow _setRotatableClient:toOrientation:updateStatusBar:duration:force:] + 954
11 UIKit 0x00588619 -[UIWindowController transition:fromViewController:toViewController:target:didEndSelector:] + 1381
12 UIKit 0x0038d65d -[UIViewController presentModalViewController:withTransition:] + 3478
13 JobAddSite 0x0000213f -[JobAddSiteViewController search] + 270
14 UIKit 0x002d94fd -[UIApplication sendAction:to:from:forEvent:] + 119
15 UIKit 0x00369799 -[UIControl sendAction:to:forEvent:] + 67
16 UIKit 0x0036bc2b -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 527
17 UIKit 0x0036a7d8 -[UIControl touchesEnded:withEvent:] + 458
18 UIKit 0x002fdded -[UIWindow _sendTouchesForEvent:] + 567
19 UIKit 0x002dec37 -[UIApplication sendEvent:] + 447
20 UIKit 0x002e3f2e _UIApplicationHandleEvent + 7576
21 GraphicsServices 0x01741992 PurpleEventCallback + 1550
22 CoreFoundation 0x00dca944 CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION + 52
23 CoreFoundation 0x00d2acf7 __CFRunLoopDoSource1 + 215
24 CoreFoundation 0x00d27f83 __CFRunLoopRun + 979
25 CoreFoundation 0x00d27840 CFRunLoopRunSpecific + 208
26 CoreFoundation 0x00d27761 CFRunLoopRunInMode + 97
27 GraphicsServices 0x017401c4 GSEventRunModal + 217
28 GraphicsServices 0x01740289 GSEventRun + 115
29 UIKit 0x002e7c93 UIApplicationMain + 1160
30 JobAddSite 0x00001dec main + 102
31 JobAddSite 0x00001d7d start + 53
)
terminate called after throwing an instance of 'NSException'
Just try this one:
if ([person objectForKey:#"position"]) {..}
This one is the same but maybe more readable:
if ([person objectForKey:#"position"] != nil) {..}
Hi Use the following code.
It is working Well.
Download Supporting Files
NSMutableArray *empArray = [[NSMutableArray alloc] init];
SBJSON *parser = [[SBJSON alloc] init];
NSURLRequest *request1 = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.bestitjobs.co.uk/appresults3.php"]]];
NSLog(#"GGGG:%#",request1);
NSData *response1 = [NSURLConnection sendSynchronousRequest:request1 returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response1 encoding:NSUTF8StringEncoding];
NSDictionary *statuses = [parser objectWithString:json_string error:nil];
NSLog(#"List Dictionary:%#",statuses);
NSArray* people =[statuses objectForKey:#"jobs"];
for(NSDictionary *test in people)
{
[empArray addObject:[test valueForKey:#"position"]];
}
NSLog(#"EMP ARRAY CATEGORY:%#",empArray);
Note: Before you Use SBJSon supporting files and import JSON.h
And check your console.
Check condition like this and add value to Array
for (NSDictionary *person in people) {
NSLog(#"people %#",people);
NSString *position = [person objectForKey:#"position"];
if(position) {
[tempArray addObject: position];
}
}

CoreLocation 0x34456f78 -[CLLocationManager onClientEventRegistered:] + 384

I am facing this error, I want to know where I am wrong.
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x80000008
Crashed Thread: 0
Thread 0 name: Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0 libobjc.A.dylib 0x34499c98 objc_msgSend + 16
1 CoreLocation 0x34456f78 -[CLLocationManager onClientEventRegistered:] + 384
2 CoreLocation 0x34457f42 -[CLLocationManager onClientEvent:supportInfo:] + 46
3 CoreLocation 0x34455a64 OnClientEvent + 16
4 CoreLocation 0x3445178a CLClientInvokeCallback(__CLClient*, CLClientEvent, __CFDictionary const*) + 46
5 CoreLocation 0x344528cc CLClientHandleDaemonDataRegistration(__CLClient*, CLDaemonCommToClientRegistration const*, __CFDictionary const*) + 700
6 CoreLocation 0x34453d50 CLClientHandleDaemonData(__CFMessagePort*, long, __CFData const*, void*) + 220
7 CoreFoundation 0x3094e706 __CFMessagePortPerform + 242
8 CoreFoundation 0x30957a90 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 20
9 CoreFoundation 0x30959838 __CFRunLoopDoSource1 + 160
10 CoreFoundation 0x3095a606 __CFRunLoopRun + 514
11 CoreFoundation 0x308eaebc CFRunLoopRunSpecific + 224
12 CoreFoundation 0x308eadc4 CFRunLoopRunInMode + 52
13 GraphicsServices 0x30269418 GSEventRunModal + 108
14 GraphicsServices 0x302694c4 GSEventRun + 56
15 UIKit 0x30a10d62 -[UIApplication _run] + 398
16 UIKit 0x30a0e800 UIApplicationMain + 664
17 ProjectOne 0x00002918 main (main.m:14)
18 ProjectOne 0x000028cc start + 32
My code :
Start Location :
-(void)startLocationTracing
{
self.TlocationManager = [[CLLocationManager alloc] init];//allocate memeory to locationmanager
self.TlocationManager.desiredAccuracy = kCLLocationAccuracyBest; //Be as accurate as possible
self.TlocationManager.distanceFilter = kCLLocationAccuracyBest;
self.TlocationManager.delegate = self;
[self.TlocationManager startUpdatingLocation];
}
Delegate Method :
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
lat = [NSString stringWithFormat:#"%3.5f",
newLocation.coordinate.latitude];
lng = [NSString stringWithFormat:#"%3.5f",
newLocation.coordinate.longitude];
CLLocation *loc_old = [[CLLocation alloc] initWithLatitude:oldLocation.coordinate.latitude longitude:oldLocation.coordinate.longitude];
CLLocation *loc_new = [[CLLocation alloc] initWithLatitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.longitude];
//get the current distance from the old distance
CLLocationDistance dist = [loc_old distanceFromLocation:loc_new];
// test the age of the location measurement to determine if the measurement is cached
// in most cases you will not want to rely on cached measurement
NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
if (locationAge > 5.0)
{
NSLog(#":::::::Location age is greate then 5.0 ::::::::");
[loc_old release];
[loc_new release];
return;
}
float dist_ = (float)dist;//distance in float
NSLog(#"%f", dist_);
[loc_old release];
[loc_new release];
NSString *str_LastLat = [NSString stringWithFormat:#"%#", [[NSUserDefaults standardUserDefaults] valueForKey:#"LastLat"]];
NSString *str_LastLong = [NSString stringWithFormat:#"%#", [[NSUserDefaults standardUserDefaults] valueForKey:#"LastLong"]];
if(([str_LastLat isEqualToString:lat]) && ([str_LastLong isEqualToString:lng]))
{
//if same lat and long arrives then do not save in the database
NSLog(#"old and new location are same");
}
else
{
if((newLocation.horizontalAccuracy > 0 ) || (newLocation.verticalAccuracy > 0) ){
[self stopTracingLocations];//to stop location services after the data is sent to
objGlobal = [[Global alloc] init];
[objGlobal postLocateValue:lat :lng type:#"TRACING"]; // WCF HIT
[objGlobal release];
}
}
}
Stop Location :
-(void)stopTracingLocations
{
[self.TlocationManager stopUpdatingLocation];
self.TlocationManager.delegate = nil;
if(self.TlocationManager){
[self.TlocationManager release];
}
}
Well it could be due to the fact you are leaking/assining incorectly"
-(void)startLocationTracing {
self.TlocationManager = [[[CLLocationManager alloc] init] autorelease];//allocate memeory to locationmanager
self.TlocationManager.desiredAccuracy = kCLLocationAccuracyBest; //Be as accurate as possible
self.TlocationManager.distanceFilter = kCLLocationAccuracyBest;
self.TlocationManager.delegate = self;
[self.TlocationManager startUpdatingLocation];
}
-(void)stopTracingLocations {
[self.TlocationManager stopUpdatingLocation];
self.TlocationManager.delegate = nil;
self.TlocationManager = nil;
}
I had the same error. It turns out I was allocating the location manager twice. You might want to see if you're doing that somehow.
It happened to me because I had a sub class calling a super method on init. That super.init allocated a location manager. I forgot about that and allocated it again in the sub classing class.

Crash With WebView in iPhone

I get following crash when I open a URL consecutively for 3 to 4 times in my app inside a webView.
Exception Type: EXC_BAD_ACCESS (SIGBUS)
Exception Codes: EXC_ARM_DA_ALIGN at 0x0062006f
Crashed Thread: 0
Thread 0 Crashed:
0 libSystem.B.dylib 0x0000576c OSAtomicCompareAndSwap32 + 0
1 libobjc.A.dylib 0x000066ce changeInfo(class_t*, unsigned int, unsigned int) + 22
2 libobjc.A.dylib 0x00008412 realizeClass(class_t*) + 38
3 libobjc.A.dylib 0x0000862c prepareForMethodLookup + 44
4 libobjc.A.dylib 0x0000538a lookUpMethod + 34
5 libobjc.A.dylib 0x00002b82 _class_lookupMethodAndLoadCache + 6
6 libobjc.A.dylib 0x000028b8 objc_msgSend_uncached + 20
7 UIKit 0x001d68c2 -[UIWebView webView:didFinishLoadForFrame:] + 214
8 UIKit 0x001d5e0c -[UIWebViewWebViewDelegate webView:didFinishLoadForFrame:] + 16
9 CoreFoundation 0x0009f06c __invoking___ + 60
10 CoreFoundation 0x00032706 -[NSInvocation invoke] + 102
11 WebCore 0x00044d42 SendMessage(NSInvocation*) + 10
12 WebCore 0x0005846e HandleDelegateSource(void*) + 62
13 CoreFoundation 0x00071a86 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 6
14 CoreFoundation 0x00073768 __CFRunLoopDoSources0 + 376
15 CoreFoundation 0x00074504 __CFRunLoopRun + 224
16 CoreFoundation 0x0001d8e4 CFRunLoopRunSpecific + 224
17 CoreFoundation 0x0001d7ec CFRunLoopRunInMode + 52
18 GraphicsServices 0x000036e8 GSEventRunModal + 108
19 GraphicsServices 0x00003794 GSEventRun + 56
20 UIKit 0x000062a0 -[UIApplication _run] + 396
21 UIKit 0x00004e10 UIApplicationMain + 664
What could be wrong?
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSLog(#"Button Clicked!");
return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
orkutURLString = #"";
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:TRUE];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSURL *currentURL = orkutWebView.request.mainDocumentURL;
NSLog(#"Relative URL: %#",[currentURL relativePath]);
NSArray *urllistItems = [[currentURL relativePath] componentsSeparatedByString:#"/"];
if([urllistItems count]>1)
{
orkutURLString = [urllistItems objectAtIndex:1];
orkutURLString = [orkutURLString lowercaseString];
if([orkutURLString isEqualToString:#"share"])
{
orkutWebView = nil;
[orkutWebView removeFromSuperview];
[orkutView removeFromSuperview];
NSString *message1 = NSLocalizedStringFromTableInBundle( #"Your status update was sent", #"Localizable", [NewfoxRadioAppDelegate GetLocalizebundle], #"");
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:#"Newfox Radio" message:message1 delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
}
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE];
}
Got the solution. Got an NSZombie wherein I was releasing the object and then trying to access it. Got the desired result after I made use of Instruments to find out the NSZombie.

IPhone - Crash in core data - multiple managed object context

So, i'm using core data with multiple thread. each one gets his own Managed object context.
I get an unrecognized selector exception , so I'm curious if I'm doing something wrong.
The crash is obviously related to the "mergeChanges" method.
I would greatly appreciate any help.
Edit
The problem seems to be that the myManagedObjectContext returns a deallocated object.
How could that be ?
My code:
- (NSManagedObjectContext *) myManagedObjectContext {
NSManagedObjectContext * result = [[[NSThread currentThread] threadDictionary] objectForKey: AQPerThreadManagedObjectContext];
if ( result != nil )
return result;
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator!=nil)
{
NSManagedObjectContext * moc = [[NSManagedObjectContext alloc] init];
[moc setMergePolicy: NSMergeByPropertyObjectTrumpMergePolicy];
[moc setPersistentStoreCoordinator: coordinator];
[self StoreManagedObjectContextForCurrentThread:moc];
[moc release]; // now owned by the thread dictionary
return moc ;
}
else {
GTMLoggerError(#"FAILED TO return managed object context ");
}
return nil;
}
-(void) StoreManagedObjectContextForCurrentThread:(NSManagedObjectContext*) context
{
[[[NSThread currentThread] threadDictionary] setObject: context forKey: AQPerThreadManagedObjectContext];
}
-(BOOL) saveChanges
{
BOOL success = YES;
NSManagedObjectContext* moc = [self myManagedObjectContext];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
selector:#selector(mergeChanges:)
name:NSManagedObjectContextDidSaveNotification
object:moc];
NSError *error = nil;
if ([moc save:&error] == NO)
{
success = NO;
GTMLoggerError(#"Failed to save to data store: [%#], [%#]",
[error localizedDescription],
[error userInfo]);
}
return success;
}
- (void)mergeChanges:(NSNotification *)notification
{
NSManagedObjectContext* moc = [self myManagedObjectContext];
AppDelegate * delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *mainContext = [delegate mainThreadMOC];
// Merge changes into the main context on the main thread
[mainContext performSelectorOnMainThread:#selector(mergeChangesFromContextDidSaveNotification:)
withObject:notification
waitUntilDone:YES];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc removeObserver:self name:NSManagedObjectContextDidSaveNotification object:moc];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
mainThreadMOC = [[NSManagedObjectContext alloc]init];
[mainThreadMOC setMergePolicy: NSMergeByPropertyObjectTrumpMergePolicy];
[mainThreadMOC setPersistentStoreCoordinator: [[DatabaseManager sharedManager] persistentStoreCoordinator]];
[[DatabaseManager sharedManager] StoreManagedObjectContextForCurrentThread:mainThreadMOC];
.....
.....
}
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSKeyPathExpression _processReferenceQueue:]: unrecognized selector sent to instance 0xa65940'
0 CoreFoundation 0x3587a987 __exceptionPreprocess + 114
1 libobjc.A.dylib 0x34a8249d objc_exception_throw + 24
2 CoreFoundation 0x3587c133 -[NSObject(NSObject) doesNotRecognizeSelector:] + 102
3 CoreFoundation 0x35823aa9 ___forwarding___ + 508
4 CoreFoundation 0x35823860 _CF_forwarding_prep_0 + 48
5 CoreData 0x356ea3d5 -[NSManagedObjectContext(_NSInternalNotificationHandling) _processReferenceQueue:] + 24
6 CoreData 0x3573032b -[NSManagedObjectContext mergeChangesFromContextDidSaveNotification:] + 842
7 CoreFoundation 0x35818bbf -[NSObject(NSObject) performSelector:withObject:] + 22
8 Foundation 0x31181795 __NSThreadPerformPerform + 268
9 CoreFoundation 0x358307dd __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 12
10 CoreFoundation 0x358025b7 __CFRunLoopDoSources0 + 382
11 CoreFoundation 0x35801e5b __CFRunLoopRun + 230
12 CoreFoundation 0x35801c87 CFRunLoopRunSpecific + 230
13 CoreFoundation 0x35801b8f CFRunLoopRunInMode + 58
14 GraphicsServices 0x320c84ab GSEventRunModal + 114
15 GraphicsServices 0x320c8557 GSEventRun + 62
16 UIKit 0x341dc329 -[UIApplication _run] + 412
17 UIKit 0x341d9e93 UIApplicationMain + 670
Not sure if this is the problem, but you should always return autoreleased-values from a function.
You're doing:
[moc release]; // now owned by the thread dictionary
return moc ;
but regardless of the ownership in the thread-dictionary, it should be:
return [moc autorelease];