Simple question about simple arrays in Objective-C - objective-c

OK this is probably a really stupid question but I can't seem to find the answer.
I know how to sort arrays using sort descriptors but what about a simple array containing only a series of numbers?
For example an array containing the following numbers:
21,3,11,58,32,76,19,45,7,92
I just need the numbers in ascending order.

I'm assuming you mean an NSArray of NSNumbers.
Fairly simple:
NSArray *unorderedNumbers; // assume exists
NSArray *sortedArray = [unorderedNumbers
sortedArrayUsingSelector:#selector(compare:)];
(See sortedArrayUsingSelector:).
This causes the objects (which happen to be numbers) to be compared using compare:.

The C standard library includes qsort
See: http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/

Related

How do I add data into NSMutableArray by manually assigning index?

Is there any way to manually control which index we want to add our data to with an NSMutableArray? In PHP, for example, we can do:
$foo[2] = "fafa";
$foo[8] = "haha";
Can the manual assigning of indexing be done on NSMutableArray?
NSMutableArrays are not sparse -- they cannot have gaps where no objects are stored. It is possible to insert an object at any index from 0 to length - 1, using insertObject:atIndex: (as Edu mentioned), but other than that you can only append objects (using addObject:).
If you need to associate objects with arbitrary integers, you can use an NSMapTable -- the functional interface allows integer keys, or simply use an NSMutableDictionary, with NSNumber keys (as drewag suggested).
See also: How to do sparse array in Cocoa
Just because it's not entirely clear to me that TeamStar wants a sparse array, I'll just mention that you can assign objects to specific indexes within an NSMutableArray – so long as the array is already long enough – using -replaceObjectAtIndex:withObject: and the other -replace… methods.
No that is not possible. I would suggest using an NSMutableDictionary instead. You can use NSNumbers as indexes.
- (void)insertObject:(id)anObject atIndex:(NSUInteger)index
Important Raises an NSRangeException if index is greater than the number of elements in the array.

taking out objects from NSMutableArray

I have an array which contains objects some may be same and some are different.
How can I take each same objects and different objects separately ?
Below is the array
NSMutableArray *items = [[NSMutableArray alloc]
initWithArray:[NSArray arrayWithObjects:#"rat", #"rat", #"cat",#"Lion", #"cat", #"dog", #"dog", nil]];
I want to have four arrays which will contains these items :
First array with two rats
2nd array with two cats
3rd array with one lion
4th array with two dogs
What could be the best way to take the objects out ? Identical object should be placed in same array.
Here's a general answer:
Put the array into an NSCountedSet - that will store each object and a count of the number of times it has been added.
Then - for each object in this counted set create an array with that object repeated according to the count of each object.
It will work in your case, because you are using static strings, which are going to be the same if they are the same string. This will take more work if you are using custom objects.
But the real question we have to ask is why you need to create these repetitive structures. If we could know what you are doing with it, we could give you better advice about how to go about it. For example, if you just need to keep a running count of the number of each type of object you have, you could just use the NSCountedSet directly (it descends from NSMutableSet, so it is already mutable) and not bother with creating the arrays.

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.

Objective C array "key" instead of index

I want to be able to use NSString, or something similar to store an array of strings, but access them by a key (I think this is what it's called), instead of a numeric index.
For example, instead of doing this:
return names[3];
Do something like this:
return names["Bob"];
How do you store and retrieve values like this?
Please excuse my lack of knowledge of this. I've been working with Objective C for about a year now, but never had to do anything like this.
In Objective-C, you do this with the NSDictionary class and its mutable subclass NSMutableDictionary. You can get the value for a key using
NSString *value = [myDictionary objectForKey:#"Bob"];
NSDictionary
Those kind of arrays are taken from C (of which Objective-C is a superset) which only allow integers as their indices.
You may wish to use NSDictionary and it's objectWithKey style messages.

Objective-C implementation of a histogram or bag datastructure

Instead of implementing my own I was wondering if anyone knows of a histogram or bag datastructure implementation in Objective-C that I can use.
Essentially a histogram is a hashmap of lists where the lists contain values that relate to their hash entry. A good example is a histogram of supermarket items where you place each group of items dairy, meat, canned goods in their own bag. You can then very easily access each group of items according to their type.
NSCountedSet is a multiset (aka "bag") that counts distinct objects, but doesn't allow duplicates. However, based on your explanation, I don't think that's what you need, and neither is a histogram, which automatically buckets values based on a set of (usually numerical) ranges.
I believe what you really want is a multimap, which is a "key to one-or-more values" relation. The data structures framework I maintain includes CHMultiDictionary, a multimap implementation. I won't claim by any means that it's perfect or complete, but I hope it may be helpful for your problem.
It sounds to me like you simply want a dictionary of arrays. You can put NSArrays as elements of NSDictionarys, something like:
NSMutableDictionary* dict = [NSMutableDictionary dictionary];
[dict setObject:[NSMutableArray arrayWithObjects:#"milk", #"eggs", #"cheese", nil] forKey:#"dairy"];
[dict setObject:[NSMutableArray arrayWithObjects:#"steak", #"sausages", #"mince", nil] forKey:#"meat"];
[[dict objectForKey:#"meat"] addObject:#"lamb"];
NSLog( #"Dictionary is %#", dict );
There's one in the GNU Objective-C Class library, but the docs appear to be pretty incomplete and the project's homepage must be currently having a problem -- still, if GPL software is acceptable for your project, you might want to download and check the sources.
CFIOMultimap apparently is an implementation of a multimap. However, as of the time of writing I couldn't get it to work. It returns nils all the time when I subscript.
Perhaps it can be fixed and adapted for your use.