-3

I'm so fedup with NSDate string object. currently I am generating an unique id on the bases of NSDate as follows:

NSDate *current_date = [[NSDate date]retain];
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"HHmmssddMMYY"];
NSString *unique_id=[df stringFromDate:current_date];
NSString  *   current_Test_id=[NSString stringWithString:unique_id];
NSLog(@"current_test_idString %@",current_Test_id);

The code above is generating unique id and prints successfully but if I am printing or accessing currtent_Test_id in another IBAction method then app crashes.

mmmmmm
  • 32,227
  • 27
  • 88
  • 117
Bhoopi
  • 6,523
  • 3
  • 22
  • 16

4 Answers4

1

Use this Method

 - (NSString *)stringDateFromDate: (NSDate *) date{

    NSDateFormatter *df = [[NSDateFormatter alloc]init];
    [df setDateFormat:@"HHmmssddMMYY"]; 
    NSString *current_Test_id=[NSString stringWithString:[df stringFromDate:date]];
    [df release];
    NSLog(@"current_tst_id %@",current_Test_id);

    return current_Test_id;

}

Call Method Like that

NSString  *current_tst_id = [self stringDateFromDate:[NSDate date]];
junaidsidhu
  • 3,539
  • 1
  • 27
  • 49
1

stringWithString will create an autorelease string, modify your code as

NSString  *   current_Test_id = [[NSString stringWithString:unique_id]retain];
ask4asif
  • 676
  • 4
  • 10
0

an NSString (or any object, for that matter) created with a class method, and not an init method, will be autoreleased. This means on the next iteration of the event loop, current_Test_id is released, and now you have a pointer to a dead object.

See this similar question

Community
  • 1
  • 1
Phil Frost
  • 3,668
  • 21
  • 29
0

As current_Test_id is instance method.

in the init (in case of mac os) or viewDidLoad (for ios) alloc+init it.

and then assign :

current_Test_id=[NSString stringWithString:unique_id]; //it will be in autorelease mode.

or

current_Test_id=[[NSString stringWithString:unique_id]retain];
Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140