-[NSFileManager removeItemAtPath:error:] makes app CRASH - iphone

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.

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

Error when presenting dates I stored in sqlite3 db in iphone development

I get this error when trying to to represent the stored dates
my question is what is this error ?
error:
2011-11-13 10:06:36.001 Holiday[217:207] -[NSNull cc_componentsForMonthDayAndYear]: unrecognized selector sent to instance 0x259ed68
2011-11-13 10:06:36.039 Holiday[217:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull cc_componentsForMonthDayAndYear]: unrecognized selector sent to instance 0x259ed68'
*** Call stack at first throw:
(
0 CoreFoundation 0x02534b99 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x0268440e objc_exception_throw + 47
2 CoreFoundation 0x025366ab -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
3 CoreFoundation 0x024a62b6 ___forwarding___ + 966
4 CoreFoundation 0x024a5e72 _CF_forwarding_prep_0 + 50
5 Holiday 0x00008c7e +[KalDate dateFromNSDate:] + 44
6 Holiday 0x0000fc36 -[KalViewController loadedDataSource:] + 265
7 Holiday 0x000081d4 -[HolidaySqliteDataSource loadHolidaysFrom:to:delegate:] + 873
8 Holiday 0x00008560 -[HolidaySqliteDataSource presentingDatesFrom:to:delegate:] + 97
9 Holiday 0x0000f848 -[KalViewController reloadData] + 162
10 Holiday 0x0000fe16 -[KalViewController showAndSelectDate:] + 276
11 Holiday 0x000065ab -[HolidayAppDelegate showAndSelectToday] + 90
12 UIKit 0x002e27f8 -[UIApplication sendAction:to:from:forEvent:] + 119
13 UIKit 0x004ee68b -[UIBarButtonItem(UIInternal) _sendAction:withEvent:] + 156
14 UIKit 0x002e27f8 -[UIApplication sendAction:to:from:forEvent:] + 119
15 UIKit 0x0036dde0 -[UIControl sendAction:to:forEvent:] + 67
16 UIKit 0x00370262 -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 527
17 UIKit 0x0036ee0f -[UIControl touchesEnded:withEvent:] + 458
18 UIKit 0x003063d0 -[UIWindow _sendTouchesForEvent:] + 567
19 UIKit 0x002e7cb4 -[UIApplication sendEvent:] + 447
20 UIKit 0x002ec9bf _UIApplicationHandleEvent + 7672
21 GraphicsServices 0x02d90822 PurpleEventCallback + 1550
22 CoreFoundation 0x02515ff4 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
23 CoreFoundation 0x02476807 __CFRunLoopDoSource1 + 215
24 CoreFoundation 0x02473a93 __CFRunLoopRun + 979
25 CoreFoundation 0x02473350 CFRunLoopRunSpecific + 208
26 CoreFoundation 0x02473271 CFRunLoopRunInMode + 97
27 GraphicsServices 0x02d8f00c GSEventRunModal + 217
28 GraphicsServices 0x02d8f0d1 GSEventRun + 115
29 UIKit 0x002f0af2 UIApplicationMain + 1160
30 Holiday 0x00001fd4 main + 102
31 Holiday 0x00001f65 start + 53
32 ??? 0x00000001 0x0 + 1
)
terminate called after throwing an instance of 'NSException'
presenting function code :
- (void)loadHolidaysFrom:(NSDate *)fromDate to:(NSDate *)toDate delegate:(id<KalDataSourceCallbacks>)delegate
{
NSLog(#"Fetching holidays from the database between %# and %#...", fromDate, toDate);
sqlite3 *db;
NSDateFormatter *fmt = [[[NSDateFormatter alloc] init] autorelease];
if(sqlite3_open([[self databasePath] UTF8String], &db) == SQLITE_OK) {
const char *sql = "select name, country, date_of_event from holidays where date_of_event between ? and ?";
sqlite3_stmt *stmt;
if(sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) == SQLITE_OK) {
[fmt setDateFormat:#"yyyy-MM-dd hh:mm:ss"];
sqlite3_bind_text(stmt, 1, [[fmt stringFromDate:fromDate] UTF8String], -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 2, [[fmt stringFromDate:toDate] UTF8String], -1, SQLITE_STATIC);
[fmt setDateFormat:#"yyyy-MM-dd"];
while(sqlite3_step(stmt) == SQLITE_ROW) {
NSString *name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 0)];
NSString *country = [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 1)];
NSString *dateAsText = [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 2)];
[holidays addObject:[Holiday holidayNamed:name country:country date:[fmt dateFromString:dateAsText]]];
}
}
sqlite3_finalize(stmt);
}
sqlite3_close(db);
[delegate loadedDataSource:self];
}
insert function, which insert dates
-(NSNumber*) insertDate: (NSDate*) d
{
NSLog(#"inserting date into database");
sqlite3 *db;
NSNumber *re = [NSNumber numberWithInt:-1];
NSDateFormatter *fmt = [[[NSDateFormatter alloc]init]autorelease];
if(sqlite3_open([[self databasePath]UTF8String],&db)==SQLITE_OK){
const char *sql = "insert into holidays(name, country, date_of_event) values(?,?,?)";
sqlite3_stmt *addStmt;
if(sqlite3_prepare_v2(db,sql,-1,&addStmt,NULL)==SQLITE_OK){
[fmt setDateFormat:#"yyyy-MM-dd hh:mm:ss"];
NSString *country = #"country test";
NSString *name =#"name test";
sqlite3_bind_text(addStmt,1,[name UTF8String],-1,SQLITE_STATIC);
sqlite3_bind_text(addStmt,2,[country UTF8String],-1,SQLITE_STATIC);
sqlite3_bind_text(addStmt,3,[[fmt stringFromDate:d]UTF8String],-1,SQLITE_STATIC);
}
if(SQLITE_DONE != sqlite3_step(addStmt)){
NSAssert1(0,#"Error in inserting into database %s",sqlite3_errmsg(db));
}else {
re = [NSNumber numberWithInt: sqlite3_last_insert_rowid(db)];
sqlite3_finalize(addStmt);
sqlite3_close(db);
}
}
return re;
}
I received the same error message. My solution required that I "chop" the time off of my date string. Another words truncate "2013-06-03 13:42:34 +0000" to "2013-06-03". The Kal function called by holiday wanted only the date.
The problem is, Kal takes NSDate as input in its internal methods. So make sure your object has NSDate and not NSString!

Leak with Mutable Array even when released

Instruments point to this line saying there is a leak here
- (void) loadFavoriteData {
TradePortMobileAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [delegate managedObjectContext];
NSManagedObjectModel *objectModel = [[context persistentStoreCoordinator] managedObjectModel];
Session *session = delegate.session;
NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys: [session objectForKey:#"CTY_CODE"], pCOUNTRY, nil];
NSFetchRequest *fetchRequest = [objectModel fetchRequestFromTemplateWithName:#"fetchAllFavorites" substitutionVariables:param];
[fetchRequest setSortDescriptors: self.dataSorter];
NSError *error;
//THIS IS THE LINE INSTRUMENT SAYS THERE IS A LEAK!!!!!
NSMutableArray *favorites = [[context executeFetchRequest:fetchRequest error:&error] mutableCopy];
if ([favorites count] > 0) {
[self.favoriteList removeAllObjects];
for (NSInteger i=0; i < [favorites count]; i++) {
FavoriteData *favorite = [favorites objectAtIndex: i];
if (i < vMaxRecordsInCoreData) {
[self.favoriteList addObject:[FavoriteInfo favoriteInfoWithClientId:favorite.clientId withName:favorite.name
withAddress:favorite.address
withPhone:favorite.phone
withEmail:favorite.email
withCountry:favorite.country
withLtpId:favorite.ltpId
withUpdateTimestamp:favorite.updateTimestamp
withNoOfDetails:favorite.noOfDetails]];
}
else {
[context deleteObject:favorite];
}
}
if (![context save:&error]) {
NSLog(#"deleting excess favorites failed.");
}
self.navigationItem.leftBarButtonItem.enabled = YES;
}
else {
[self.favoriteList removeAllObjects];
self.navigationItem.leftBarButtonItem.enabled = NO;
}
[favorites removeAllObjects];
[favorites release];
}
This is the stack
0 CoreFoundation _CFRuntimeCreateInstance
1 CoreFoundation __CFStringCreateImmutableFunnel3
2 CoreFoundation CFStringCreateWithCString
3 CoreData -[NSSQLCore _prepareResultsFromResultSet:usingFetchPlan:withMatchingRows:]
4 CoreData -[NSSQLCore _newRowsForFetchPlan:selectedBy:withArgument:]
5 CoreData -[NSSQLCore newRowsForFetchPlan:]
6 CoreData -[NSSQLCore objectsForFetchRequest:inContext:]
7 CoreData -[NSSQLCore executeRequest:withContext:error:]
8 CoreData -[NSPersistentStoreCoordinator executeRequest:withContext:error:]
9 CoreData -[NSManagedObjectContext executeFetchRequest:error:]
MY CODE HERE--->10 TradePortMobile -[FavoritesTableViewController loadFavoriteData] /Users/aldrich/Projects/iPhone/Classes/FavoritesTableViewController.m:281
11 TradePortMobile -[FavoritesTableViewController viewWillAppear:] /Users/aldrich/Projects/iPhone/Classes/FavoritesTableViewController.m:54
12 UIKit -[UINavigationController viewWillAppear:]
13 UIKit -[UITabBarController transitionFromViewController:toViewController:transition:shouldSetSelected:]
14 UIKit -[UITabBarController transitionFromViewController:toViewController:]
15 UIKit -[UITabBarController _setSelectedViewController:]
16 UIKit -[UITabBarController _tabBarItemClicked:]
17 UIKit -[UIApplication sendAction:to:from:forEvent:]
18 UIKit -[UITabBar _sendAction:withEvent:]
19 UIKit -[UIApplication sendAction:to:from:forEvent:]
20 UIKit -[UIControl sendAction:to:forEvent:]
21 UIKit -[UIControl(Internal) _sendActionsForEvents:withEvent:]
22 UIKit -[UIControl sendActionsForControlEvents:]
23 UIKit -[UIApplication sendAction:to:from:forEvent:]
24 UIKit -[UIControl sendAction:to:forEvent:]
25 UIKit -[UIControl(Internal) _sendActionsForEvents:withEvent:]
26 UIKit -[UIControl touchesEnded:withEvent:]
27 UIKit -[UIWindow _sendTouchesForEvent:]
28 UIKit -[UIApplication sendEvent:]
29 UIKit _UIApplicationHandleEvent
30 GraphicsServices PurpleEventCallback
31 CoreFoundation __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__
32 CoreFoundation __CFRunLoopDoSource1
33 CoreFoundation __CFRunLoopRun
34 CoreFoundation CFRunLoopRunSpecific
35 CoreFoundation CFRunLoopRunInMode
36 GraphicsServices GSEventRunModal
37 GraphicsServices GSEventRun
38 UIKit UIApplicationMain
39 TradePortMobile main /Users/aldrich/Projects/iPhone/main.m:14
40 TradePortMobile start
May somebody give me a push to the right direction? or an answer to this leak i can not solve :)
The leak tool can only point to where the memory has been allocated, the leak is probably happening as you are passing some of the properties of each object from the array in the following code:
[self.favoriteList addObject:[FavoriteInfo favoriteInfoWithClientId:favorite.clientId withName:favorite.name
withAddress:favorite.address
withPhone:favorite.phone
withEmail:favorite.email
withCountry:favorite.country
withLtpId:favorite.ltpId
withUpdateTimestamp:favorite.updateTimestamp
withNoOfDetails:favorite.noOfDetails]];
you need to check what happens with the parameters of favoriteInfoWithClientId:favorite - if you retain any of these then you will have a leak...
hope this helps

AddressBook Crash, only with some contacts

My app crashes, it is a problem that arises from the AddressBook API, it only happens with some contacts.
Here is the log:
Exception Type: EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x00000102, 0x316ebd38
Crashed Thread: 0
Thread 0 Crashed:
0 CoreFoundation 0x00001cfe CFRetain + 90
1 AddressBook 0x00004b2c ABCMultiValueCopyValueAtIndex + 28
2 AddressBook 0x0001066a ABMultiValueCopyValueAtIndex + 2
3 Call Monitor 0x00003824 -[CallAppDelegate peoplePickerNavigationController:shouldContinueAfterSelectingPerson:property:identifier:] (AppDelegate.m:408)
4 AddressBookUI 0x00032cfc -[ABPeoplePickerNavigationController personViewController:shouldPerformDefaultActionForPerson:property:identifier:withMemberCell:] + 152
5 AddressBookUI 0x0003b8ce -[ABPersonViewControllerHelper personTableViewDataSource:selectedPropertyAtIndex:inPropertyGroup:withMemberCell:forEditing:] + 222
6 AddressBookUI 0x0004a17c -[ABPersonTableViewDataSource valueAtIndex:selectedForPropertyGroup:withMemberCell:forEditing:] + 40
7 AddressBookUI 0x00048c00 -[ABPersonTableViewDataSource tableView:didSelectRowAtIndexPath:] + 316
8 UIKit 0x00091f40 -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] + 656
9 UIKit 0x0009db40 -[UITableView _userSelectRowAtIndexPath:] + 124
10 Foundation 0x00086c86 __NSFireDelayedPerform + 362
11 CoreFoundation 0x00071a54 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 8
12 CoreFoundation 0x00073ede __CFRunLoopDoTimer + 854
13 CoreFoundation 0x0007485e __CFRunLoopRun + 1082
14 CoreFoundation 0x0001d8e4 CFRunLoopRunSpecific + 224
15 CoreFoundation 0x0001d7ec CFRunLoopRunInMode + 52
16 GraphicsServices 0x000036e8 GSEventRunModal + 108
17 GraphicsServices 0x00003794 GSEventRun + 56
18 UIKit 0x000062a0 -[UIApplication _run] + 396
19 UIKit 0x00004e10 UIApplicationMain + 664
20 Call Monitor 0x000028e8 main (main.m:14)
21 Call Monitor 0x000028b8 start + 32
This is driving me crazy, as it only happens with an isolated number of contacts.
Any help would be greatly appreciated.
Here is the code that was requested, thank you very very much for your help:
(It is an extract from the method where I think the error happens)
The weird thing is that it only happens with certain contacts, and deleting the contact, then creating a new one solves the problem...
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
NSString* firstName = (NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
NSString* lastName = (NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
NSNumber* record = [NSNumber numberWithInt:ABRecordGetRecordID(person)];
if(lastName!=nil){
name=[NSString stringWithFormat:#"%# %#",firstName,lastName];
}
else {
name=firstName;
}
ABMultiValueRef phone = ABRecordCopyValue(person, property);
NSString *value =(NSString *)ABMultiValueCopyValueAtIndex(phone, identifier);
NSString *label =(NSString *)ABMultiValueCopyLabelAtIndex(phone, identifier);
NSMutableArray *tempArray=[[NSMutableArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:#"MainArray"]];
NSDictionary *stringDictionary = [NSDictionary dictionaryWithObjectsAndKeys:name, kLabelKey, value, kNumberKey,label, kNumberLabelKey,record, kReferenceKey, nil];
[tempArray addObject:stringDictionary];
NSArray *mainArray = [NSArray arrayWithArray:tempArray];
[[NSUserDefaults standardUserDefaults] setObject:mainArray forKey:#"MainArray"];
To anyone experiencing a similar problem:
My error came from the fact that I was using:
ABMultiValueCopyValueAtIndex with an identifier instead of an index.
You have to call ABMultiValueGetIndexForIdentifier and then use that index on the ABMultiValueCopyValueAtIndex.
The bottom line is Identifier!=index.
Instead of using
ABMultiValueCopyValueAtIndex(multiValue, identifier);
Which Zebs pointed out above, use...
ABMultiValueCopyValueAtIndex(multiValue, ABMultiValueGetIndexForIdentifier(multiValue, identifier));
I would make sure you're really dealing with valid multi value record type.
if (ABMultiValueGetPropertyType(phone) != kABInvalidPropertyType) {
// Do work here.
}
Actually, it would probably be safer to make sure it's really a string.
if (ABMultiValueGetPropertyType(phone) == kABMultiStringPropertyType) {
// Do work here.
}
I don't know why this wouldn't be the case. Maybe you have corrupted contacts entries? Or maybe sometimes the phone number isn't a multi value type?