How to convert objective C array to a C array? - objective-c

I have NSArray in Objective C, which store int only. How can I convert it to C array? Thanks.
My Objective C array:
NSArray *myArray = [[NSArray alloc] initWithObject:#"1", #"4", #"8", nil];

Allocate a chunk of memory using malloc to hold enough of the items (in this case, NSString*s and iterate over the NSArray, adding each item (and retaining each item) into an appropriate position in the c array.
Don't forget in doing this, you will have to send a release message to each member in the c array when you're done with it, before you also have to free() the array itself.

I guess you cannot explicitly since an NSArray encapsulates a C array, but an array of pointers to the objects referenced. So the better you can get is to retrieve (in reality copy) that array of pointers.
If you want to get the value of the objects you need to 'query' them for their values, have a look here

Related

array of char * in objective c

I have a c string and need it to break it up into lines (I wont make a NSString of them at this moment).
Is there something like an NSMutableArray where I can put this char * in?
Or how can I achieve it to make something from the strings what I can access later by index?
Currently I make
char *cline = strtok(data, "\n");
while(cline)
{
...
}
Or is it easier todo this when I read the file from disk?
Use an NSValue to store your char* in an NSMutableArray
Overview
An NSValue object is a simple container for a single C or Objective-C data item. It can hold any of the scalar types such as int, float, and char, as well as pointers, structures, and object ids. The purpose of this class is to allow items of such data types to be added to collections such as instances of NSArray and NSSet, which require their elements to be objects. NSValue objects are always immutable.
You cannot insert a C/C++ pointer into an NSMutableArray, unless it is wrapped in a container like an NSValue or other Objective-C class.
It would be a lot easier, if you want an NSMutableArray, to just convert it to an NSString.
NSArray* strings = [[NSString initWithCString:data encoding:NSUTF8StringEncoding] componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]];
Your other options, if you strictly want to stay in the C/C++ realm would be to have a vector of strings or an array of char*.
As others have already pointed out, to store primitive C types such as a in an Obj-C object such as an instance of NSMutableArray, you would need to wrap them in NSValue objects first.
As an alternative to doing this - if you are wanting to work with pure C strings in Obj-C, don't forget that you can freely mix C with Objective-C source code, so using a normal C array is a perfectly legitimate solution too.
By wrapping the values into an obj-c array you gain the bounds checking and mutability, but if you keep unwrapping the values to work on them as a C string, you might be better sticking with a plain old C string to begin with, to save the overhead.
If you then want to make an NSString, you can simply use the NSString convenience method stringWithFormat:, like so:
char str[50];
// read characters into the buffer from a file...
// When done, convert to an NSString:
NSString *string = [NSString stringWithFormat:#"%s", str];

Objective C - difference between dictionaries and arrays?

in Objective C - what is the difference between dictionaries and arrays? Are dictionaries used with key : value (where Key can be any object), and arrays are id : value (where id is an integer)?
thanks
Array
In Objective-C, an array is a type of collection which can store object types. It can store any type of objects. Objects stored in an array are linked to their index number.
eg. if you create an array and insert the first object, it will be stored in "index 0"
and, the index number will keep on increasing from 0,1,2....n
Use "NSMutableArray" to create an array that can be modified.
example,
NSMutableArray *array = [NSMutableArray alloc] init];
[array addObject:#"Tom"];
[array addObject:#"Cat"];
So, at index 0, you will have "Tom". And, at index 1, you will have "Cat".
Dictionary
In Objective-C, a dictionary is a type of collection that stores "key-value" pairs.
The "key" is of type ID, so you can enter any object as key for a value.
Use "NSMutableDictionary" to create a dictionary that can be modified.
example,
NSMutableDictionary *dictionary = [NSMutableDictionary alloc] init];
[dictionary setObject:#"Tom" forkey:#"name"];
[dictionary setObject:#"Cat" forKey:#"animal"];
The key difference between array and dictionary is the sequence of the objects gets changed in a dictionary, while in an array the sequence of objects stored is SEQUENTIAL.
[EDIT]
Since there has been quite a discussion with regard to this answer, I will make it clear that the array does NOT get re-created as some comments say.
The size of array/dictionary gets dynamically increased to accomodate the new elements in the colletion.

Better way to convert NSArray of NSNumbers to array of NSStrings

I have an NSArray consisting of NSNumbers and I want to convert this to an NSArray of NSStrings, by getting the stringValue of each NSNumber in the first array.
The method that comes to my mind is iterating each value in the first one, getting its string value and adding it into another array. But there should be a more elegant solution for this. Do you know one?
NSArray implements the Key-Value Coding method valueForKey: in such a way that it returns a new array. The new array contains the results of asking each object in the original array for the specified value. In this case, NSNumber has its stringValue, so all you have to do is:
NSArray * b = [a valueForKey:#"stringValue"];
Plain old fast enumeration (or enumerateObjectsUsingBlock:) wouldn't be a terrible solution, though. NSArray's implementation of valueForKey: most likely uses a for loop internally, and that would be pretty readily understood by anyone who reads it later.

appending array in objective c

i read this command from cocoadev.com but was not able to get it plz help me in explaining what this line of code do
[array addObject:[NSNumber numberWithInt:15]];
You have to use NSMutableArray instead of NSArray to use the method addObject:.
It adds a number object with the integer value of 15 to the collection (presumably an NSMutableArray) called array.

Objective C creating custom arrays

In other languages I could create a class then use this to create an array of objects in that class eg class price which is used in a performance class to define a price[] prices;
in objective C i cant get this to work, how do you do it?
The price class is an inherit of NSObject, can I use NSMutableArray?
If you have a class Price, and it inherits from NSObject, then you can have an array of them stored in an NSArray or NSMutableArray. You could also store them in a C array, or an STL vector, although the memorymanagement sematics may be difficult in those cases.
In the case of an NSArray/NSMutableArray, the array takes an ownership reference on the object, so you can release it after adding it to the array, and it will remain in memory until it is removed from the array (and all other locations).
Code might look like:
NSMutableArray* a = [NSMutableArray array];
[a addObject:[Price price]];
// and/or
[a addObject:[[[Price alloc] init] autorelease];
// and/or
Price* p = [[Price alloc] init];
[a addObject:p];
[p release];
NSLog( #"The array is %#", a );
// Remember at this point you do not "own" a, retain it if you want to keep it, or use [NSMutableArray new] above
When a is released, all the Price objects it contains will be released (and potentially deallocated).
Yes, NSMutableArray is what you would want to use.
To answer your last question first: if you are storing instances of Objective-C object (which, as you say, inherit from NSObject) then yes, use NSMutableArray. However, this won't work for primitive types (like int, BOOL, char, char*, etc.).
Objective-C uses the C way of declaring arrays with one caveat: you can't allocate memory on the stack (which is what that does in C), only on the heap. That means you have to use malloc (prefer NSAllocateCollectable() on Leopard or later) and free to manage the memory. Also, you declare the array as a pointer to an array or pointers. Something like this: (Note: pulled from thin air, untested.)
Price **prices = malloc(numberOfEntries * sizeof(Price*));
...
free(prices);
Using an NSMutableArray is generally much easier than managing your own arrays. Just be aware of the memory management rules: collections call -retain on an object when it is inserted, and -release on it when it is removed (or on all objects if the collection is deallocated).