I am getting this error on my project in Xcode;
NSRangeException
[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array
I think the line is here in my initial controller.m file;
Session *item = [dataArray objectAtIndex:0];
NSString* strDate = [LoadSessionController GetTimeString:item.mCreateDate];
cell1.title = #"Restore last session";
cell1.date = strDate;
cell1.ago = [LoadSessionController GetBeforeTimeString:item.mCreateDate];
cell1.image = item.mThumbnail;
cell1.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell1.selectionStyle = UITableViewCellSelectionStyleBlue;
cell = cell1;
break;
}
As the crash log is this;
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Crashed Thread: 0
Last Exception Backtrace:
0 CoreFoundation 0x328c429e __exceptionPreprocess + 158
1 libobjc.A.dylib 0x395a697a objc_exception_throw + 26
2 CoreFoundation 0x3280fb70 -[__NSArrayM objectAtIndex:] + 160
3 ColorSplash 0x0001722a 0x1000 + 90666
4 UIKit 0x3861f540 -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:withIndexPath:] + 408
5 UIKit 0x38604306 -[UITableView(_UITableViewPrivate) _updateVisibleCellsNow:] + 1306
6 UIKit 0x3861b7c2 -[UITableView layoutSubviews] + 202
7 UIKit 0x385d77fe -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 254
8 QuartzCore 0x3a2abd5e -[CALayer layoutSublayers] + 210
9 QuartzCore 0x3a2ab8fc CA::Layer::layout_if_needed(CA::Transaction*) + 456
10 QuartzCore 0x3a2ac830 CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 12
11 QuartzCore 0x3a2ac216 CA::Context::commit_transaction(CA::Transaction*) + 234
12 QuartzCore 0x3a2ac024 CA::Transaction::commit() + 312
13 UIKit 0x385dd8e6 _afterCACommitHandler + 122
14 CoreFoundation 0x328996c8 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 16
15 CoreFoundation 0x328979bc __CFRunLoopDoObservers + 272
16 CoreFoundation 0x32897d12 __CFRunLoopRun + 738
17 CoreFoundation 0x3280aeb8 CFRunLoopRunSpecific + 352
18 CoreFoundation 0x3280ad44 CFRunLoopRunInMode + 100
19 GraphicsServices 0x35d4f2e6 GSEventRunModal + 70
20 UIKit 0x386282f4 UIApplicationMain + 1116
But I am convinced the array isn't empty, but perhaps the newer version of iOS requires a different answer to just the :0
Any help would be much appreciated,
Thanks,
Chris
EDIT - Some more info;
- (void)viewDidLoad
{
CGRect frame = CGRectMake(0, 0, SCN_WIDTH, SCN_HEIGHT);
[self.view setFrame: frame];
self.dataArray = [LoadSessionController loadTableData:NO];
self.tableView.rowHeight = ROW_HEIGHT;
}
...Loadsessioncontroller is;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *kCustomCellID = #"MyCellID";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:kCustomCellID];
if (cell == nil)
{
cell = (CustomCell *)[[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:kCustomCellID] autorelease];
}
Session *item = [dataArray objectAtIndex:[self getDataIndex:indexPath.row]];
NSString* strDate = [LoadSessionController GetTimeString:item.mCreateDate];
cell.title = #"Load saved session";
cell.date = strDate;
cell.ago = [LoadSessionController GetBeforeTimeString:item.mCreateDate];
cell.image = item.mThumbnail;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
NSInteger TimeSort(Session *obj1, Session *obj2, void *reverse) {
if ((NSInteger *)reverse == NO) {
if ([obj1.mCreateDate timeIntervalSinceNow] < [obj2.mCreateDate timeIntervalSinceNow])
return NSOrderedAscending;
else
return NSOrderedDescending;
}
else {
if ([obj1.mCreateDate timeIntervalSinceNow] > [obj2.mCreateDate timeIntervalSinceNow])
return NSOrderedAscending;
else
return NSOrderedDescending;
}
}
+ (NSMutableArray*) loadTableData:(BOOL) bLoadRestoreData
{
NSMutableArray* ret = [[NSMutableArray alloc] init];
NSString* path =[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
int i;
int nStartNo = 1;
if (bLoadRestoreData)
nStartNo = 0;
for (i = nStartNo; i < 100; i++)
{
if ([Session exist:path index:i])
{
Session* one = [[Session alloc] init];
[one read:path index:i];
[ret addObject:one];
[one release];
}
}
[ret sortUsingFunction:TimeSort context:self];
return ret;
}
+ (NSString*) GetTimeString:(NSDate *)date
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:
(kCFCalendarUnitHour|kCFCalendarUnitMinute|kCFCalendarUnitYear|kCFCalendarUnitMonth|kCFCalendarUnitDay) fromDate:date];
//[dateFormatter stringFromDate:date]
return [NSString stringWithFormat:#"Saved %02d/%02d/%02d %02d:%02d", components.year, components.month, components.day,
components.hour, components.minute];
}
#define TIME_SUFFIX(a) (((a)>1)?"s":"")
+ (NSString*) GetBeforeTimeString:(NSDate*) date
{
NSTimeInterval ago = [date timeIntervalSinceNow];
unsigned int temp = -ago;
int days = temp / (3600*24); temp = temp % (3600 * 24);
int hours = temp / 3600; temp = temp % 3600;
int minutes = temp / 60; temp = temp % 60;
int seconds = temp;
if (days == 0 && hours == 0 && minutes == 0)
{
return [NSString stringWithFormat:#"%d second%s ago",
seconds, TIME_SUFFIX(seconds)];
}
else if (days == 0 && hours == 0)
{
return [NSString stringWithFormat:#"%d minute%s %d second%s ago",
minutes, TIME_SUFFIX(minutes), seconds, TIME_SUFFIX(seconds)];
}
else if (days == 0)
{
return [NSString stringWithFormat:#"%d hour%s %d minute%s ago",
hours, TIME_SUFFIX(hours), minutes, TIME_SUFFIX(minutes)];
}
else {
return [NSString stringWithFormat:#"%d day%s %d hour%s ago",
days, TIME_SUFFIX(days), hours, TIME_SUFFIX(hours)];
}
}
"But I am convinced the array isn't empty, but perhaps the newer version of iOS requires a different answer to just the :0"
No, this is not the case. Your array is definitely empty. Just log your array before the statement where you think the problem is, and see what you get. If you need to check whether an array is empty, you can either check if array.count is 0 or if array.lastObject is nil.
As your error message says, your dataArray is empty. Either you don't fill it at all, or you access it before filling it.
The array is empty for sure, verify it through an assertion:
NSAssert( [dataArray count] >=1, #"Array is empty");
Then post the code with which you think to fill the array.
Related
[__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.
My application is attempting to use a zombie instance of something, though i have no idea where the problem is. the exception consistently occurs when invoking (IBAction)addTag:sender.
my stack trace is below:
2012-03-12 17:06:45.935 FavoriteTwitterSearches[3636:f803] -[__NSCFString addTag:]: unrecognized selector sent to instance 0x6a30d90
2012-03-12 17:06:45.943 FavoriteTwitterSearches[3636:f803] CRASH: -[__NSCFString addTag:]: unrecognized selector sent to instance 0x6a30d90
2012-03-12 17:06:45.947 FavoriteTwitterSearches[3636:f803] Stack Trace: (
0 CoreFoundation 0x013bc06e __exceptionPreprocess + 206
1 libobjc.A.dylib 0x0154dd0a objc_exception_throw + 44
2 CoreFoundation 0x013bdced -[NSObject doesNotRecognizeSelector:] + 253
3 CoreFoundation 0x01322f00 ___forwarding___ + 432
4 CoreFoundation 0x01322ce2 _CF_forwarding_prep_0 + 50
5 CoreFoundation 0x013bdec9 -[NSObject performSelector:withObject:withObject:] + 73
6 UIKit 0x000165c2 -[UIApplication sendAction:to:from:forEvent:] + 96
7 UIKit 0x0001655a -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 61
8 UIKit 0x000bbb76 -[UIControl sendAction:to:forEvent:] + 66
9 UIKit 0x000bc03f -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 503
10 UIKit 0x000bb2fe -[UIControl touchesEnded:withEvent:] + 549
11 UIKit 0x0003ba30 -[UIWindow _sendTouchesForEvent:] + 513
12 UIKit 0x0003bc56 -[UIWindow sendEvent:] + 273
13 UIKit 0x00022384 -[UIApplication sendEvent:] + 464
14 UIKit 0x00015aa9 _UIApplicationHandleEvent + 8196
15 GraphicsServices 0x012a6fa9 PurpleEventCallback + 1274
16 CoreFoundation 0x013901c5 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 53
17 CoreFoundation 0x012f5022 __CFRunLoopDoSource1 + 146
18 CoreFoundation 0x012f390a __CFRunLoopRun + 2218
19 CoreFoundation 0x012f2db4 CFRunLoopRunSpecific + 212
20 CoreFoundation 0x012f2ccb CFRunLoopRunInMode + 123
21 GraphicsServices 0x012a5879 GSEventRunModal + 207
22 GraphicsServices 0x012a593e GSEventRun + 114
23 UIKit 0x00013a9b UIApplicationMain + 1175
24 FavoriteTwitterSearches 0x00001fab main + 187
25 FavoriteTwitterSearches 0x00001ee5 start + 53
26 ??? 0x00000001 0x0 + 1
)
objc[3636]: EXCEPTIONS: finishing handler
Support Files/Main.m:
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
void uncaughtExceptionHandler(NSException *exception);
int main(int argc, char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int retVal;
#try {
retVal = UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
#catch (NSException *exception) {
NSLog(#"CRASH: %#", exception);
NSLog(#"Stack Trace: %#", [exception callStackSymbols]);
}
#finally {
[pool release];
}
return retVal;
}
Controller.m
#import "Controller.h"
#implementation Controller
- (id)init
{
if (self != nil)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *dir = [paths objectAtIndex:0];
filePath = [[NSString alloc] initWithString:[dir stringByAppendingPathComponent:#"tagsIndex.plist"]];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:filePath] == NO)
{
tags = [[NSMutableDictionary alloc] init];
}
else
{
tags = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
}
buttons = [[NSMutableArray alloc] init];
infoButtons = [[NSMutableArray alloc] init];
}
return self;
}
- (void)awakeFromNib
{
for (NSString *title in tags)
[self addNewButtonWithTitle:title];
}
- (void)refreshList
{
for (UIButton *button in scrollView.subviews)
[button removeFromSuperview];
[infoButtons removeAllObjects];
float buttonOffset = BUTTON_SPACING;
for (UIButton *button in buttons)
{
CGRect buttonFrame = button.frame;
buttonFrame.origin.x = BUTTON_SPACING;
buttonFrame.origin.y = buttonOffset;
buttonFrame.size.width = scrollView.frame.size.width - BUTTON_SPACING - BUTTON_HEIGHT;
buttonFrame.size.height = BUTTON_HEIGHT;
button.frame = buttonFrame;
UIButton *infobutton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[infoButtons addObject:infobutton];
buttonFrame = infobutton.frame;
buttonFrame.origin.x = scrollView.frame.size.width - BUTTON_SPACING - SCROLLBAR_WIDTH;
buttonFrame.origin.y = buttonOffset;
infobutton.frame = buttonFrame;
[infobutton
addTarget:self action:#selector(infoButtonTouched:)
forControlEvents:UIControlEventTouchUpInside];
[scrollView addSubview:infobutton];
buttonOffset += BUTTON_HEIGHT + BUTTON_SPACING;
}
}
- (void)infoButtonTouched:sender
{
int index = [infoButtons indexOfObject:sender];
NSString *key = [[buttons objectAtIndex:index] titleLabel].text;
tagField.text = key;
NSString *value = [tags valueForKey:key];
queryField.text = value;
}
- (IBAction)addTag:sender
{
[tagField resignFirstResponder];
[queryField resignFirstResponder];
NSString *key = tagField.text;
NSString *value = queryField.text;
if (value.length == 0 || key.length == 0) return;
if ([tags valueForKey:key] == nil)
[self addNewButtonWithTitle:key];
[tags setValue:value forKey:key];
tagField.text = nil;
queryField.text = nil;
[tags writeToFile:filePath atomically:NO];
}
- (IBAction)clearTags:sender
{
[tags removeAllObjects];
[tags writeToFile:filePath atomically:NO];
[buttons removeAllObjects];
[self refreshList];
}
- (void)addNewButtonWithTitle:(NSString *)title
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:title forState:UIControlStateNormal];
[button
addTarget:self action:#selector(buttonTouched:)
forControlEvents:UIControlEventTouchUpInside];
[buttons addObject:button];
[buttons sortUsingSelector:#selector(compareButtonTitles:)];
[self refreshList];
CGSize contentSize = CGSizeMake(
scrollView.frame.size.width,
buttons.count * (BUTTON_HEIGHT + BUTTON_SPACING) + BUTTON_SPACING);
[scrollView setContentSize:contentSize];
}
- (void)buttonTouched:sender
{
NSString *key = [sender titleLabel].text;
NSString *search = [[tags valueForKey:key]
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *urlString = [NSString stringWithFormat:
#"http://search.twitter.com/search?q=%#", search];
NSURL *url = [NSURL URLWithString:urlString];
[[UIApplication sharedApplication] openURL:url];
}
- (void)dealloc
{
[filePath release];
[tags release];
[infoButtons release];
[buttons release];
[super dealloc];
}
#end
#implementation UIButton (sorting)
- (NSComparisonResult)compareButtonTitles:(UIButton *)button
{
return [self.titleLabel.text caseInsensitiveCompare:button.titleLabel.text];
}
#end
[__NSCFString addTag:]: unrecognized selector sent to instance says thay you are calling method addTag: on an instance of type NSString.
Check to what object and how is your IBAction connected in your xib. If everything is okey, try to clean your project, reset your simulator, and then try it again.
EDIT: please, add a NSLog into your dealloc to check if your controller has not been deallocated.
It sounds like most likely a Controller object is getting deallocated prematurely. It's not possible from the code you've posted to tell where it's happening, but you should be able to track it down with Instruments (zombies and malloc stack logging in particular). Or, if Controller isn't used in a lot of places†, it might be quicker just to look there and see if you're mistakenly autoreleasing it.
†For an object called something like "Controller", I wouldn't bet on it, but it's worth mentioning and being able to easily track the life cycle of objects is a great incentive to reduce coupling in your program designs.
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.
in my application i have a table view and a detail view. The table view is populated from a database query. I have this database methods in the viewDidLoad method (i don't know where else to put it) Then i have the [self.tableView reload] method in the viewWillAppear method. The problem is that when i go back from the detail view to the table view and click the same element (in the table view) the application crashes. I guess it is because the database methods are still running when i come back from the detail view and i click on a cell. So the data in the table view is never reloaded. Do you guys have any idea on how to fix this?
*EDIT:
*Here's the code from the database, i use it to populate the table view:*
- (void)viewDidLoad
{
//Convert the course id to string
NSString *selectedCategoryIdConverted = [NSString stringWithFormat:#"%d", self.selectedCategory._id];
NSMutableArray *tempArray = [[NSMutableArray alloc]init];
// Set up sqlite statement
sqlite3_stmt *dbStatement = nil;
NSString *sqlQuery = [NSString stringWithFormat:#"SELECT co.name, co.id, o.location FROM course as co JOIN categories as ca JOIN occasions as o WHERE co.catID = ca.id AND co.catID = %i AND o.courseID = co.id", self.selectedCategory._id];
//Convert the query string to const char
const char *sqlQueryConverted =[sqlQuery UTF8String];
int prepareSqlQuery = sqlite3_prepare_v2( [[DatabaseController sharedDatabaseController] getDb], sqlQueryConverted, -1, &dbStatement, NULL);
//Run the query
while ( sqlite3_step(dbStatement) == SQLITE_ROW )
{
const char *name = (const char *)sqlite3_column_text(dbStatement, 0);
int courseId = sqlite3_column_int(dbStatement, 1);
const char *location = (const char *)sqlite3_column_text(dbStatement, 2);
//Convert the returnedElement char to string
NSString *nameConverted = [[[NSString alloc] initWithUTF8String:name] autorelease];
NSString *locationConverted = [[[NSString alloc] initWithUTF8String:location] autorelease];
Course *course = [[Course alloc] initWithName:nameConverted _id:courseId location:locationConverted];
[tempArray addObject:course];
}
self.courses = tempArray;
[super viewDidLoad];
}
EDIT: I noticed that when i go back to the table view, the app won't crash if i click on the next element, but if i click on the previous element (row) in the table view the app crashes.
EDIT: I changed the code to the viewDidAppear method and fixed memory leaking. self.courses is (nonatomic, retain) here's the code:
- (void)viewWillAppear:(BOOL)animated
{
//Convert the course id to string
//NSString *selectedCategoryIdConverted = [NSString stringWithFormat:#"%d", self.selectedCategory._id];
NSMutableArray *tempArray = [[NSMutableArray alloc]init];
// Set up sqlite statement
sqlite3_stmt *dbStatement = nil;
NSString *sqlQuery = [NSString stringWithFormat:#"SELECT co.name, co.id, o.location FROM course as co JOIN categories as ca JOIN occasions as o WHERE co.catID = ca.id AND co.catID = %i AND o.courseID = co.id", self.selectedCategory._id];
//Convert the query string to const char
const char *sqlQueryConverted =[sqlQuery UTF8String];
int prepareSqlQuery = sqlite3_prepare_v2( [[DatabaseController sharedDatabaseController] getDb], sqlQueryConverted, -1, &dbStatement, NULL);
//Run the query
while ( sqlite3_step(dbStatement) == SQLITE_ROW )
{
const char *name = (const char *)sqlite3_column_text(dbStatement, 0);
int courseId = sqlite3_column_int(dbStatement, 1);
const char *location = (const char *)sqlite3_column_text(dbStatement, 2);
//Convert the returnedElement char to string
NSString *nameConverted = [[[NSString alloc] initWithUTF8String:name] autorelease];
NSString *locationConverted = [[[NSString alloc] initWithUTF8String:location] autorelease];
Course *course = [[Course alloc] initWithName:nameConverted _id:courseId location:locationConverted];
[tempArray addObject:course];
[course release];
course = nil;
}
self.courses = tempArray;
[tempArray release];
[self.tableView reloadData];
[super viewWillAppear:animated];
}
EDIT: Here's is the error log:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIDeviceWhiteColor _id]: unrecognized selector sent to instance 0x4d2e2a0'
Call stack at first throw:
(
0 CoreFoundation 0x010435a9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x01197313 objc_exception_throw + 44
2 CoreFoundation 0x010450bb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
3 CoreFoundation 0x00fb4966 ___forwarding___ + 966
4 CoreFoundation 0x00fb4522 _CF_forwarding_prep_0 + 50
5 BookApp 0x000079e8 -[CoursesCategoriesViewController viewWillAppear:] + 184
6 UIKit 0x0017c9be -[UINavigationController _startTransition:fromViewController:toViewController:] + 858
7 UIKit 0x0017732a -[UINavigationController _startDeferredTransitionIfNeeded] + 266
8 UIKit 0x0017e562 -[UINavigationController pushViewController:transition:forceImmediate:] + 932
9 UIKit 0x001771c4 -[UINavigationController pushViewController:animated:] + 62
10 BookApp 0x000056d6 -[CoursesViewController tableView:didSelectRowAtIndexPath:] + 374
11 UIKit 0x00135b68 -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] + 1140
12 UIKit 0x0012bb05 -[UITableView _userSelectRowAtPendingSelectionIndexPath:] + 219
13 Foundation 0x0084579e __NSFireDelayedPerform + 441
14 CoreFoundation 0x010248c3 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 19
15 CoreFoundation 0x01025e74 __CFRunLoopDoTimer + 1220
16 CoreFoundation 0x00f822c9 __CFRunLoopRun + 1817
17 CoreFoundation 0x00f81840 CFRunLoopRunSpecific + 208
18 CoreFoundation 0x00f81761 CFRunLoopRunInMode + 97
19 GraphicsServices 0x012d81c4 GSEventRunModal + 217
20 GraphicsServices 0x012d8289 GSEventRun + 115
21 UIKit 0x000ccc93 UIApplicationMain + 1160
22 BookApp 0x00001ff9 main + 121
23 BookApp 0x00001f75 start + 53
)
terminate called after throwing an instance of 'NSException'
From your stack trace, the interesting parts are :
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIDeviceWhiteColor _id]: unrecognized selector sent to instance 0x4d2e2a0'
and
5 BookApp 0x000079e8 -[CoursesCategoriesViewController viewWillAppear:] + 184
which corresponds to :
- (void)viewWillAppear:(BOOL)animated {
//...
NSString *sqlQuery =
[NSString stringWithFormat:
#"SELECT co.name, co.id, o.location FROM course as co JOIN categories as ca JOIN occasions as o WHERE co.catID = ca.id AND co.catID = %i AND o.courseID = co.id",
self.selectedCategory._id]; // << The culprit
//...
You get this because self.selectedCategory._id tries to send an _id message to self.selectedCategory and fails, self.selectedCategory not being the good type.
How could this be possible?
Since I guess you are sure that self.selectedCategory is the expected type...
Simply because self.selectedCategory has been released, and its address has been reused for another variable... of another type, in your trace a UIColor instance... Could be anything else.
Conclusion
Double check your retain/release of that self.selectedCategory property :)
Side note
+1 for the FMDB suggestion... A must!
Your code is leaking memory. You are not putting release after assigning temp array to self.courses. Also you are not releasing course object after adding it to temp array. For SQLite operations I suggest you to use FMDB. It will be very easier to manage then putting SQL queries in each view controller to fetch the data from database. Also It's a bad practice to follow this kind of pattern. Use FMDB for all your sqlite purpose. Create a seperate class for all the sqlite communication.
I am using this code and it is giving exception
NSMutableArray *streams = (NSMutableArray *)[feed valueForKey:#"comments"];
NSMutableArray *streams1 = (NSMutableArray *)[streams valueForKey:#"data"];
//NSMutableArray *streams2 = (NSMutableArray *)[streams1 valueForKey:#"message"];
// loop over all the stream objects and print their titles
int index;
NSMutableDictionary *stream;
for (index = 0; index < [feed count];index++) {
stream = (NSMutableDictionary *)[streams1 objectAtIndex:index];
NSLog(#"Name of sender is: %#", [stream valueForKey:#"message"]);
}
FaceBookTable *detailViewController = [[FaceBookTable alloc] initWithNibName:#"FaceBookTable" bundle:nil];
// ...
// Pass the selected object to the new view controller.
detailViewController.fbGraph = fbGraph;
detailViewController.dummyArray = [ feed valueForKey:#"message"];
detailViewController.dict = stream;
}
Exception is
-[__NSArrayI isEqualToString:]: unrecognized selector sent to instance 0x5dae960
2011-06-15 16:14:07.835 MultiSocial[8042:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI isEqualToString:]: unrecognized selector sent to instance 0x5dae960'
while my other code is working fine
NSMutableArray *streams = (NSMutableArray *)[feed valueForKey:#"from"];
lueForKey:#"message"];
// loop over all the stream objects and print their titles
int index;
NSMutableDictionary *stream;
for (index = 0; index < [feed count];index++) {
stream = (NSMutableDictionary *)[streams objectAtIndex:index];
NSLog(#"Name of sender is: %#", [stream valueForKey:#"message"]);
}
Please help
here is crash log
2011-06-15 17:05:42.148 MultiSocial[8583:207] -[__NSArrayI isEqualToString:]: unrecognized selector sent to instance 0x5d05f50
2011-06-15 17:05:42.156 MultiSocial[8583:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI isEqualToString:]: unrecognized selector sent to instance 0x5d05f50'
*** Call stack at first throw:
(
0 CoreFoundation 0x013cabe9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x0151f5c2 objc_exception_throw + 47
2 CoreFoundation 0x013cc6fb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
3 CoreFoundation 0x0133c366 ___forwarding___ + 966
4 CoreFoundation 0x0133bf22 _CF_forwarding_prep_0 + 50
5 UIKit 0x00649405 -[UITableViewLabel setText:] + 84
6 MultiSocial 0x00046147 -[FaceBookTable tableView:cellForRowAtIndexPath:] + 467
7 UIKit 0x0045f7fa -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:withIndexPath:] + 634
8 UIKit 0x0045577f -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:] + 75
9 UIKit 0x0046a450 -[UITableView(_UITableViewPrivate) _updateVisibleCellsNow:] + 1561
10 UIKit 0x00462538 -[UITableView layoutSubviews] + 242
11 QuartzCore 0x01e98451 -[CALayer layoutSublayers] + 181
12 QuartzCore 0x01e9817c CALayerLayoutIfNeeded + 220
13 QuartzCore 0x01e9137c _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 310
14 QuartzCore 0x01e910d0 _ZN2CA11Transaction6commitEv + 292
15 QuartzCore 0x01ec17d5 _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 99
16 CoreFoundation 0x013abfbb __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 27
17 CoreFoundation 0x013410e7 __CFRunLoopDoObservers + 295
18 CoreFoundation 0x01309bd7 __CFRunLoopRun + 1575
19 CoreFoundation 0x01309240 CFRunLoopRunSpecific + 208
20 CoreFoundation 0x01309161 CFRunLoopRunInMode + 97
21 GraphicsServices 0x0190f268 GSEventRunModal + 217
22 GraphicsServices 0x0190f32d GSEventRun + 115
23 UIKit 0x003fa42e UIApplicationMain + 1160
24 MultiSocial 0x00002740 main + 102
25 MultiSocial 0x000026d1 start + 53
)
Well as per the crash log -[__NSArrayI isEqualToString:] there is some mistake in your code. It is clearly visible in the crash report that isEqualToString method is for NSString object but in your code it is called on NSArray.
Just debug your app and you will find the solution.
UPDATE
//Make sure that feed return an array for the key comments
NSArray *streams = (NSArray *)[feed valueForKey:#"comments"];
NSArray *streams1 = (NSArray *)[streams valueForKey:#"data"];
NSLog(#"comments : %#",streams);
//When you are running loop only last index value will be copied into your dictionary named stream so remove the loop.
FaceBookTable *detailViewController = [[FaceBookTable alloc] initWithNibName:#"FaceBookTable" bundle:nil];
// ...
// Pass the selected object to the new view controller.
detailViewController.fbGraph = fbGraph;
detailViewController.dummyArray = [ feed valueForKey:#"message"];
detailViewController.dict = streams;
}
//Your tableView cellForRowAtIndexPath method should look like this
//First get the dictionary
if(dict){
NSDictionary *stream = (NSDictionary *)[dict objectAtIndex:indexPath.row];
if(stream){
NSDictionary * messages = (NSDictionary *[stream valueForKey:#"Message"];
NSString *comment = [messages valueForKey:#"comment"];
cell.textLabel.text = comment;
}
}
u have been assigning the NSString object to NSArray.so do debug with breakpoints
NSMutableArray *arr = [[[feed valueForKey:#"comments"]valueForKey:#"data" ]valueForKey:#"id"];
for (NSString* cid in [arr objectAtIndex:0]) {
NSLog(#"cid is : %# \n\n",cid);
}