Array in Objective C (iPhone)
I want to ask about the NSArray in objective C.
I want to create a dynamic array as I don't know about the size 开发者_Go百科of the array. And I also want to insert some of the data to the array. However, I don't know how to decl, init and insert the element in to the array.
The following is the C++ version. I want to create a empty array A and put all the array element in array B to A.
// empty array
string arrA[] = new string();
// put the arrB into arrA
for(int i=0; i < arrB.length(); i++)
arrA[i] = arrB[i];
Thank you very much.
You should use the class named NSArray
or NSMutableArray
. These are similar to std::vector
however they are somewhat different in their use due to the way Objective-C works.
// Immutable array (must be created with contents specified)
NSArray *strings = [NSArray arrayWithObjects:@"Hello", @", world!", nil];
// Mutable array (can be modified)
NSMutableArray *strings = [NSMutableArray array];
[strings addObject:@"Hello"];
[strings addObject:@", world!"];
The difference with Objective-C NSArray
objects is that they can take any type of object as long as it is a subclass of NSObject
.
NSArray *array = [NSArray arrayWithObjects:@"A string", [NSNumber numberWithInt:1337], [NSDictionary dictionary]];
To access values you must use the objectAtIndex:
message.
NSString *aString = [array objectAtIndex:10];
NSLog(aString);
Use a NSMutableArray
. If arrB
is a NSArray
:
NSMutableArray *arrA = [[NSMutableArray alloc] init];
[arrA addObjectsFromArray: arrB];
Here is the documentation: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableArray/addObjectsFromArray:
精彩评论