0

I am new at objective c,

I am taking two dates and getting the number of days in between:

NSString *start = @"2010-12-01";
NSString *end = @"2010-12-02";

NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:@"yyyy-MM-dd"];
NSDate *startDate = [f dateFromString:start];
NSDate *endDate = [f dateFromString:end];

NSDateComponents *components;
NSInteger days;

components = [[NSCalendar currentCalendar] components: NSDayCalendarUnit
fromDate: startDate toDate: endDate options: 0];

days = [components day];

When I try to assign days to cell.textLable.text = days, but I get this error message:

Thread 1: EXC_BAD_ACCESS(code=1, address=0x1)

cell is this SGridAutoMultiLineCell *cell; what does error mean and how do I fix it. the number that is being returned is 1.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
user979331
  • 11,039
  • 73
  • 223
  • 418
  • Same mistake: [NSDateComponents EXC_BAD_ACCESS error](http://stackoverflow.com/q/2226286) – jscs Dec 10 '14 at 20:29
  • I dont understand there answer, should I try cell.textLabel.text = NSLog(@"%ld", days) ? – user979331 Dec 10 '14 at 20:39
  • 3
    Probably more like `cell.textLabel.text = [NSString stringWithFormat:@"%d", days];`. – nobody Dec 10 '14 at 20:41
  • I would recommend that you have a look at [Good resources for learning ObjC](http://stackoverflow.com/q/1374660). The Big Nerd Ranch books are excellent, and lots of people like the Stanford iOS course on iTunes U. – jscs Dec 10 '14 at 20:46

2 Answers2

8

Try:

cell.textLabel.text = [NSString stringWithFormat:@"%d", days];

Your current code (cell.textLable.text = days;) is passing an integer to a field that expects an NSString pointer. When the component tries to dereference that value (1) as a pointer, the crash occurs because 1 is not currently a valid memory location.

The code above will construct an NSString containing the days value.

nobody
  • 19,814
  • 17
  • 56
  • 77
1

You're assigning an integer value (1, the number of days between Dec 1st and 2nd) to the label which expects an instance of NSString. This is why the error message says the address is 0x1- it is treating the integer value of 1 as an address of an object in memory. As pointed out in the comments it's necessary to first convert the integer to a string. The easiest way is using -stringWithFormat: but you may want to perform locale-specific formatting.

sbooth
  • 16,646
  • 2
  • 55
  • 81