how to create an C Array - iphone

his guys,
i think this is a simple question but i do not know how to do it.
how do i create the line below dynamically from an array?
this is what i need to call.
//data source
NSString * sourceData[7] = {#"2", #"1", #"4", #"8", #"14", #"15", #"10"};
chartData = [WSData dataWithValues:[WSData arrayWithString:sourceData withLen:7]];
+ (NSArray *)arrayWithString:(NSString *[])strings
withLen:(NSUInteger)len {
NSMutableArray *tmpArr = [NSMutableArray
arrayWithCapacity:len];
NSUInteger i;
for (i=0; i<len; i++) {
[tmpArr addObject:strings[i]];
}
return [NSArray arrayWithArray:tmpArr];
}
thanks for all the help especially Daniel :)
this is the answer to the question
NSMutableArray * dayArray = [[NSMutableArray alloc] init];
dayArray = [NSMutableArray arrayWithCapacity:7];
NSMutableArray * sdArray = [[NSMutableArray alloc] init];
sdArray = [NSMutableArray arrayWithCapacity:7];
NSInteger drunked = [appDelegate.drinksOnDayArray count];
if (drunked !=0)
{
for(int i=6; i>=0; i--)
{
DayOfDrinks *drinksOnDay = [appDelegate.drinksOnDayArray objectAtIndex:i];
NSString * dayString= [NSDate stringForDisplayFromDateForChart:drinksOnDay.dateConsumed];
[dayArray addObject:dayString];//X label for graph the day of drink.
drinksOnDay.isDetailViewHydrated = NO;
[drinksOnDay hydrateDetailViewData];
NSNumber *sdNumber = drinksOnDay.standardDrinks;
[sdArray addObject: sdNumber];
}
NSString *sData[7];// = malloc(7 * sizeof(NSString *));
for (int i=0; i<7; i++)
{
DayOfDrinks *drinksOnDay = [appDelegate.drinksOnDayArray objectAtIndex:i];
sData[i] = [NSString stringWithFormat:#"%#",drinksOnDay.standardDrinks];
}
NSString * sourceData[7] = {sData[6],sData[5],sData[4],sData[3],sData[2],sData[1],sData[0] };
}

If you are only using the array as a call parm, and are not storing it somewhere or returning it from your current method:
NSString* sourceData[7];
for (i = 0; i < 7; i++) {
int num = <getTheValueYouWant>;
sourceData[i] = [NSString stringWithFormat:#"%d", num];
}
But note that if you intend to return the array, or store it in some long-lived variable, you need an entirely different setup.

So this is how you would create an NSMutableArray. Mutable because you're creating it at runtime.
NSString * sourceData = [[NSString alloc] initWithFormat:#""];
//assuming the array you have is arr with NSNumber objects
for (NSNumber *num in arr) {
[sourceData stringByAppendingFormat:#"%#", num];
}

You can try below code with the loop as you required.....
NSMutableArray *array;
array = [[NSMutableArray alloc] init];
[array addObject:[NSNumber numberWithFloat:1.0f]];
[array release];

Related

Separate array into many in a dynamic way? Obj-C

I currently have this method:
-(void)seperateGuides
{
DLog("GetGuideListCount: %i", [[appDelegate getGuideList] count]);
columnOneArray = [[NSMutableArray alloc] init];
columnTwoArray = [[NSMutableArray alloc] init];
columnThreeArray = [[NSMutableArray alloc] init];
for (int i = 0; i < [[appDelegate getGuideList] count]; i = i + 3) {
[columnOneArray addObject:[[appDelegate getGuideList]objectAtIndex:i]];
}
for (int i = 1; i < [[appDelegate getGuideList] count]; i = i + 3) {
[columnTwoArray addObject:[[appDelegate getGuideList]objectAtIndex:i]];
}
for (int i = 2; i < [[appDelegate getGuideList] count]; i = i + 3) {
[columnThreeArray addObject:[[appDelegate getGuideList]objectAtIndex:i]];
}
}
And need to do this more dynamic, so I can define how many arrays I want and then get the arrays.
Different possibilities I'm considering is making it a mutli-dimensional array (although I'm not sure how to handle it in Objectvie-C), or making a method that simply loops through as many times as I define, the problem there is that I'm not quite sure how to get the different arrays.
A simple algorithm or another possible solution would be greatly appreciated.
The algorithm you're describing sounds equivalent to what we do when we deal a deck of cards into multiple hands, so I'd do it like this:
- (NSArray *)dealObjects:(NSArray *)objects intoArrays:(NSInteger)numArrays
{
NSMutableArray *arrays = [NSMutableArray arrayWithCapacity:numArrays];
for (a = 0; a < numArrays; a++) {
[arrays addObject:[NSMutableArray arrayWithCapacity:[objects count] / numArrays];
}
for (i = 0; i < [objects count]; i++) {
[[arrays objectAtIndex:i % numArrays] addObject:[objects objectAtIndex:i]];
}
return arrays;
}
You can add multiple array to another arrays as this,
-(void)seperateGuides:(int)columnCount
{
rootArray=[[NSMutableArray alloc] init];
for(int i=0;i<columnCount;i++)
{
column = [[NSMutableArray alloc] init];
for(int j=i;j<[[appDelegate getGuideList] count];j=j+3)
{
[column addObject:[[appDelegate getGuideList]objectAtIndex:j]];
[rootArray addObject:column];
[column release];
}
}
}
Quite simple really. Just add new NSArray objects to a root array as you iterate through your dataset.
- (void)seperateGuides {
DLog("GetGuideListCount: %i", [[AppDelegate getGuideList] count]);
NSArray *root = [[NSArray alloc] init];
int dimensions = anyIntGreaterThanZero;
for (int i = 0; i < dimensions; i += dimensions) {
NSArray *branch = [[NSArray alloc] init];
int k = 0;
for (k += i; k < [[AppDelegate getGuideList] count]; k += dimensions) {
[branch addObject:[[AppDelegate getGuideList] objectAtIndex:k]];
}
[root arrayByAddingObject:branch];
}
}
-(void)seperateGuides
{
NSMutableArray *parentArray = [[NSMutableArray alloc]init];
int count = [[appDelegate getGuideList] count];
int TOTAL_COLUMNS = 3;//Define number of columns here
for (int i = 0; i <count; i++)
{
int columnNo = i % TOTAL_COLUMNS;
if(parentArray.count > columnNo)
{
NSMutableArray *innerArray = [parentArray objectAtIndex:columnNo];
[innerArray addObject:[[appDelegate getGuideList]objectAtIndex:i]];
}
else
{
NSMutableArray *innerArray = [NSMutableArray arrayWithObject:[[appDelegate getGuideList]objectAtIndex:i]];
[parentArray insertObject:innerArray atIndex:columnNo];
}
}
}
Hope this helps...
Here parentArray will have NSMutableArray as its members. Each array represents the objects in a column.

How to sort NSMutableArray elements?

I have model class which contains NSString's- studentName, studentRank and studentImage. I wanna sort the NSMutableArray according to studentRanks. what I have done is
- (void)uploadFinished:(ASIHTTPRequest *)theRequest
{
NSString *response = nil;
response = [formDataRequest responseString];
NSError *jsonError = nil;
SBJsonParser *json = [[SBJsonParser new] autorelease];
NSArray *arrResponse = (NSArray *)[json objectWithString:response error:&jsonError];
if ([jsonError code]==0) {
// get the array of "results" from the feed and cast to NSArray
NSMutableArray *localObjects = [[[NSMutableArray alloc] init] autorelease];
// loop over all the results objects and print their names
int ndx;
for (ndx = 0; ndx < arrResponse.count; ndx++)
{
[localObjects addObject:(NSDictionary *)[arrResponse objectAtIndex:ndx]];
}
for (int x=0; x<[localObjects count]; x++)
{
TopStudents *object = [[[TopStudents alloc] initWithjsonResultDictionary:[localObjects objectAtIndex:x]] autorelease];
[localObjects replaceObjectAtIndex:x withObject:object];
}
topStudentsArray = [[NSMutableArray alloc] initWithArray:localObjects];
}
}
How can I sort this topStudentsArray according to the ranks scored by the Students and If the two or more student have the same rank, How can I group them.
I did like this
TopStudents *object;
NSSortDescriptor * sortByRank = [[[NSSortDescriptor alloc] initWithKey:#"studentRank" ascending:NO] autorelease];
NSArray * descriptors = [NSArray arrayWithObject:sortByRank];
NSArray * sorted = [topStudentsArray sortedArrayUsingDescriptors:descriptors];
but this is not displaying results properly. please help me to overcome this problem. thanks in advance.
doing something like this might do the trick
Initially sort the arrGroupedStudents in the (ascending/descending) order of studentRank
//Create an array to hold groups
NSMutableArray* arrGroupedStudents = [[NSMutableArray alloc] initWithCapacity:[topStudentsArray count]];
for (int i = 0; i < [topStudentsArray count]; i++)
{
//Grab first student
TopStudents* firstStudent = [topStudentsArray objectAtIndex:i];
//Create an array and add first student in this array
NSMutableArray* currentGroupArray = [[[NSMutableArray alloc] initWithCapacity:0] autorelease];
[currentGroupArray addObject:firstStudent];
//create a Flag and set to NO
BOOL flag = NO;
for (int j = i+1; j < [topStudentsArray count]; j++)
{
//Grab next student
TopStudents* nextStudent = [topStudentsArray objectAtIndex:j];
//Compare the ranks
if ([firstStudent.studentRank intValue] == [nextStudent.studentRank intValue])
{
//if they match add this to same group
[currentGroupArray addObject:nextStudent];
}
else {
//we have got our group so stop next iterations
[arrGroupedStudents addObject:currentGroupArray];
// We will assign j-1 to i
i=j-1;
flag = YES;
break;
}
}
//if entire array has students with same rank we need to add it to grouped array in the end
if (!flag) {
[arrGroupedStudents addObject:currentGroupArray];
}
}
Finally your arrGroupedStudents will contain grouped array with equal rank. I have not test run the code so you might need to fix a few things falling out of place. Hope it helps
If you want to display in the order of ranks, you should set the ascending as YES.
NSSortDescriptor * sortByRank = [[NSSortDescriptor alloc] initWithKey:#"studentRank" ascending:YES];
static int mySortFunc(NSDictionary *dico1, NSDictionary *dico2, void *context)
{
NSString *studentName1 = [dico1 objectForKey:#"studentName"];
NSString *studentName2 = [dico2 objectForKey:#"studentName"];
return [studentName1 compare:studentName2];
}
- (IBAction)sortBtnTouched:(id)sender
{
[topStudentsArray sortUsingFunction:mySortFunc context:NULL];
}

how to create an array of string or float in Objective-C

i need some help here, i need to know how to create an array of string retrieved from an array. i'm using powerplot for graph and it only accept float or string array.
i need to create something something like this dynamically.
NSString * sourceData[7] = {#"2", #"1", #"4", #"8", #"14", #"15", #"10"};
Below are my code to find out the numbers in strings.
NSInteger drunked = [appDelegate.drinksOnDayArray count];
NSMutableArray * dayArray = [[NSMutableArray alloc] init];
NSMutableArray * sdArray = [[NSMutableArray alloc] init];
//float *sdArray[7];
for (int i=0; i<drunked; i++) {
DayOfDrinks *drinksOnDay = [appDelegate.drinksOnDayArray objectAtIndex:i];
NSString * dayString= [NSDate stringForDisplayFromDateForChart:drinksOnDay.dateConsumed];
[dayArray addObject:dayString];
NSLog(#"%#",[dayArray objectAtIndex:i]);
drinksOnDay.isDetailViewHydrated = NO;
[drinksOnDay hydrateDetailViewData];
NSString * sdString= [NSString stringWithFormat:#"%#", drinksOnDay.standardDrinks];
[sdArray addObject:sdString];
NSString *tempstring;
NSLog(#"%#",[sdArray objectAtIndex:i]);
}
thanks for the help :)
Array's in Objectice-C aren't that hard to work with:
NSMutableArray *myArray = [NSMutableArray array];
[myArray addObject:#"first string"]; // same with float values
[myArray addObject:#"second string"];
[myArray addObject:#"third string"];
int i;
int count;
for (i = 0, count = [myArray count]; i < count; i = i + 1)
{
NSString *element = [myArray objectAtIndex:i];
NSLog(#"The element at index %d in the array is: %#", i, element); // just replace the %# by %d
}
You can either use NSArray or NSMutableArray - depending on your needs, they offer different functionality.
Following tutorial covers exactly what you are looking after:
http://www.cocoalab.com/?q=node/19
You can also add the elements to the array when you init (and optionally add them later only if you are using the Mutable version of a collection class:
NSMutableArray *myArray = [[NSMutableArray alloc] initWithObjects:#"2", #"1", #"4", #"8", #"14", #"15", #"10", nil];
[myArray addObject:#"22"];
[myArray addObject:#"50"];
//do something
[myArray release];
You can use malloc to create a C-style array. something like this should work:
NSString **array = malloc(numElements * sizeof(NSString *))
some code here
free(array)
Be aware that unlike NSMutable array, c arrays won't do a retain, so you have to manage it if needed. And don't forget the free

Converting table view to have sections

I have a table view, which has its data source from an array that contains names of people.
Now to make it easy to find people, I want to section the table view so that it has the letter A-Z on the right hand side, just like the Address Book app.
But my current array just contains a collection of NSStrings. How do I split them so that they are grouped by the first letter of the names? Is there any convenient way to do it?
EDIT: If anyone's interested in my final code:
NSMutableArray *arrayChars = [[NSMutableArray alloc] init];
for (char i = 'A'; i <= 'Z' ; i++) {
NSMutableDictionary *characterDict = [[NSMutableDictionary alloc]init];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
for (int k = 0; k < [myList count]; k++) {
NSString *currentName = [[friends objectAtIndex:k] objectForKey:#"name"];
char heading = [currentName characterAtIndex:0];
heading = toupper(heading);
if (heading == i) {
[tempArray addObject:[friends objectAtIndex:k]];
}
}
[characterDict setObject:tempArray forKey:#"rowValues"];
[characterDict setObject:[NSString stringWithFormat:#"%c",i] forKey:#"headerTitle"];
[arrayChars addObject:characterDict];
[characterDict release];
[tempArray release];
}
At the end of the function I'll have:
arrayChars [0] = dictionary(headerTitle = 'A', rowValues = {"adam", "alice", etc})
arrayChars[1] = dictionary(headerTitle = 'B', rowValues = {"Bob", etc})
Thank you everyone for your help!
You can use a dictionary to sort them, so create an array with all the letters you want to sort and a array with nil objects to initialize the dictionary
NSArray *names = #[#"javier",#"juan", #"pedro", #"juan", #"diego"];
NSArray *letters = #[#"j", #"p", #"d"];
NSMutableArray *objects = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < [letters count]; ++i)
{
[objects addObject:[[NSMutableArray alloc] init]];
}
NSDictionary *dictionary = [[NSDictionary alloc] initWithObjects:objects forKeys:letters];
Then you must find the first letter if the word and put that word into the corresponding key in the dictionary
for (NSString *name in names) {
NSString *firstLetter = [name substringToIndex:1];
for (NSString *letter in letters) {
if ([firstLetter isEqualToString:letter]) {
NSMutableArray *currentObjects = [dictionary objectForKey:letter];
[currentObjects addObject:name];
}
}
}
To check you can print directly the dictionary
NSLog(#"%#", dictionary);
Then is your work to fill your sections in the tableview using the dictionary

NSArray objects go out of scope after returning pointer

I am attempting to use the below code in a function to return an array of dictionary objects. Unfortunately, after the return to the next function in the stack all of the rows in the mutable array have become 'out of scope'. From my understanding, the array should retain the row (dictionary) object automatically so even after the return, where the row pointer goes out of scope, the row objects should still have a retain count of 1. What am I doing wrong here? How do I build this array in such a way that the objects it contains don't get released?
for (int i = 1; i < nRows; i++)
{
NSMutableDictionary* row = [[[NSMutableDictionary alloc] initWithCapacity:nColumns] ];
for(int j = 0; j < nColumns; j++)
{
NSString* key = [[NSString stringWithUTF8String:azResult[j]] ];
NSString* value = [[NSString stringWithUTF8String:azResult[(i*nColumns)+j]] ];
[row setValue:value forKey:key];
}
[dataTable addObject:row];
}
return dataTable;
This line:
NSMutableDictionary* row = [[NSMutableDictionary alloc] initWithCapacity:nColumns] ];
should use the autorelease:
NSMutableDictionary* row = [[[NSMutableDictionary alloc] initWithCapacity:nColumns] ] autorelease];
From what i understand:
-(NSMutableArray*) getArrayOfDictionaries{
int nRows=somenumber;
int nColumns=someOthernumber;
char **azResult=someArrayOfStrings;
NSMutableArray *dataTable=[[NSMutableArray alloc] init];
for (int i = 1; i < nRows; i++)
{
NSMutableDictionary* row = [[[NSMutableDictionary alloc] initWithCapacity:nColumns]];
for(int j = 0; j < nColumns; j++)
{
NSString* key = [[NSString stringWithUTF8String:azResult[j]] ];
NSString* value = [[NSString stringWithUTF8String:azResult[(i*nColumns)+j]] ];
[row setValue:value forKey:key];
}
[dataTable addObject:row];
//you should add the following line to avoid leaking
[row release];
}
//watch for leaks
return [dataTable autorelease];
//beyond this point dataTable will be out of scope
}
-(void) callingMethod {
//dataTable is out of scope here, you should look into arrayOfDictionaries variable
NSMutableArray* arrayOfDictionaries=[self getArrayOfDictionaries];
}
You should look into the local variable in callingMethod instead of dataTable which is local to the method I called getArrayOfDictionaries