PDA

View Full Version : Array Questions




Jeremy1026
Jul 21, 2008, 07:56 AM
I have a bit of a complex problem revolving around arrays.

I need to do 5 things with an array:
Create an array
Fill the array with 5 variables
Sort the variables from low to high
Remove duplicates
Find out if value1 + 1 = value2 + 1 = value3 + 1 = value4 + 1 = value5

Any help with this would be greatly appreciated.



iphonearticles
Jul 22, 2008, 04:27 PM
Hi,
Create an Array use
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:2];

Let us suppose we have a class called Artist with a property artistName. artistName is also the key when implementing the get and the set methods.

To learn more about key-value programming go here
http://developer.apple.com/documentation/Cocoa/Conceptual/KeyValueCoding/KeyValueCoding.html

Artist *object1 = [[Artist] alloc] init];
object1.artistName = @"Two";

Artist *object2 = [[Artist] alloc] init];
object2.artistName = @"One";

Add some objects to the array like this
[array addObject:object1];
[array addObject:object2];

Now to sort the array we will use NSSortDescriptor class like this
NSSortDescriptor *nsd = [[NSSortDescriptor alloc] initWithKey:@"artistName" ascending:YES];

Add the Sort Descriptor class in an array
NSMutableArray *nsdArray = [[NSMutableArray alloc] init];
[nsdArray addObject:nsd];

Now you are ready to sort the array using sortUsingDescriptor method, like this
[array sortUsingDescriptors:nsdArray];

Your array will be sorted after the above line is executed.

To remove duplicates you can use removeObjectIdenticalTo or
filterUsingPredicate. You will need to create an object of NSPredicate but it uses teh same concepts of key-value programming.

To learn more about iPhone SDK, please visit http://www.iphonesdkarticles.com

Thanks
iPhone SDK Articles