-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.

4

4 回答 4

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]];
于 2012-12-31T12:13:20.670 回答
1

stringWithString will create an autorelease string, modify your code as

NSString  *   current_Test_id = [[NSString stringWithString:unique_id]retain];
于 2012-12-31T12:14:51.403 回答
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

于 2012-12-31T12:12:26.117 回答
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];
于 2012-12-31T12:14:53.620 回答