开发者

Adding string to an array

i wanted to know how to add strings into an array.

I used the following methods but it is showing null.

1) [arrData addObject:[NSString stringWithS开发者_Python百科tring:strlast]];
2) [arrData addObject:strlast];

Thanks in advance


You can't add anything to an NSArray once it's created. You need to use an NSMutableArray if you want to make changes to it.

Update: You may actually have two problems.

  1. Using an NSArray instead of an NSMutableArray when mutability is needed.

  2. Not initializing the array object (either kind). If arrData is nil, you can happily send as many messages as you want to nil. Nothing will happen.


If it is showing null (nil) you need to make sure you set arrData somewhere in your code before trying to addObject:.

arrData = [[NSMutableArray alloc] init];

Also strlast is a string so use your second example, the first example is pointless.

[arrData addObject:strlast];


Did you allocate an array and assign it to arrData?


Try:

NSMutableArray *arrData = [NSMutableArray array];
NSString *string = @"My string";
[arrData addObject:string];
NSLog(@"%@", [arrData objectAtIndex:0]); //logs "My string"


If you're using a non-mutable array, you can also use arrayByAddingObject:

arrData = [arrData arrayByAddingObject: strlast];

but a mutable array is probably a better idea.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜