开发者

Add dynamically created string to an array

I am making an iphone app in which I want to store the dynamically selected time into an array, but unable to implement the method to store the strings into an ar开发者_开发技巧ray. Following is the code which I am using but it is not giving the output.

- (void)storetimeintoanarray:(id)sender
{
    NSDateFormatter *df3 = [[NSDateFormatter alloc] init];
    [df3 setDateFormat:@"hh:mm:ss"];
    timestr = [NSString stringWithFormat:@"%@",[df3 stringFromDate:objtimepicker.date]];
    NSLog(@"time is:%@",timestr);
    test = [[NSArray alloc]init];
    [test arrayByAddingObject:timestr];
    NSLog(@"array time:%@",test);
}


You have to declare array mutable object.

test = [[NSMutableArray alloc]init];
[test addObject:timestr];


You have to assign the result of the arrayByAddingObject: method to a new array like:

NSArray *newone = [test arrayByAddingObject:timestr];


After allocating you shouldn't allocate the array again. arrayByAddingObject returns a auto released new array. Also use a NSMutableArray when you want to add objects dynamically. Change the code to

test = [[NSMutableArray alloc]init];
[test addObject:timestr];


You should be using NSMutableArray if you want to change it after creation.

NSMutableArray* arr = [[NSMutableArray alloc] init];
[arr addObject:timestr];

To create an array with a single object, you can use:

NSArray* arr = [NSArray arrayWithObject:timestr];


You should use NSMutableArray and its method addObject: instead of NSArray. [test arrayByAddingObject:timestr]; does nothing with your array test, its create new array

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜