execute addObject, but NSMutableArray has no object - iphone

I try to use to codes below to add object to NSMutableArray
NSMutableArray* multipartData;
- (void)processDataChunk:(NSData *)postDataChunk
{
if (!postHeaderOK)
{
UInt16 separatorBytes = 0x0A0D;
NSData* separatorData = [NSData dataWithBytes:&separatorBytes length:2];
for (int i = 0; i < [postDataChunk length] - l; i++)
{
NSRange searchRange = {i, l};
if ([[postDataChunk subdataWithRange:searchRange] isEqualToData:separatorData])
{
NSRange newDataRange = {dataStartIndex, i - dataStartIndex};
dataStartIndex = i + l;
i += l - 1;
NSData *newData = [postDataChunk subdataWithRange:newDataRange];
if ([newData length])
{
[multipartData addObject:newData]; //A:set break point here
}
}
}
}
}
I set breakpoint at A:, and found that newData is not nil.
What is wrong with my codes?
Welcome any comment

You declare multipartData but do not allocate or initialize it. Somewhere before adding objects you must have
NSMutableArray *multipartData = [[NSMutableArray alloc] init];
or possibly
NSMutableArray *multipartData = [[[NSMutableArray alloc] init] autorelease];
as your needs dictate. But you must allocate and initialize multipartData before adding to or accessing anything in it.

Related

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 C Array

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];

How to solve Memory leaks for following Sqlite code?

I am getting memory leaks in Instruments in the following Sqlite Code.
NSArray *result = [self executeQuery:sql arguments:argsArray];
It calls following method.
- (NSArray *)executeQuery:(NSString *)sql arguments:(NSArray *)args {
sqlite3_stmt *sqlStmt;
if (![self prepareSql:sql inStatament:(&sqlStmt)])
return nil;
int i = 0;
int queryParamCount = sqlite3_bind_parameter_count(sqlStmt);
while (i++ < queryParamCount)
[self bindObject:[args objectAtIndex:(i - 1)] toColumn:i inStatament:sqlStmt];
NSMutableArray *arrayList = [[NSMutableArray alloc] init];
int columnCount = sqlite3_column_count(sqlStmt);
while ([self hasData:sqlStmt]) {
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
for (i = 0; i < columnCount; ++i) {
id columnName = [self columnName:sqlStmt columnIndex:i];
id columnData = [self columnData:sqlStmt columnIndex:i];
[dictionary setObject:columnData forKey:columnName];
}
[arrayList addObject:[dictionary autorelease]];
}
sqlite3_finalize(sqlStmt);
return arrayList;
}
How do I solve it ?
We'd need to see the code of your executeQuery method - it should be returning an auto-released result, but perhaps it isn't.
You could try ;
NSArray *result = [[self executeQuery:sql arguments:argsArray] autorelease];
But I'd be wary of just blindly trying that without actually seeing what executeQuery does in detail.
EDIT:
OK, here's your problem;
NSMutableArray *arrayList = [[NSMutableArray alloc] init];
Either create it as an auto-released array, or finish the method with;
return [arrayList autorelease];

Memory Leak according to Instruments

Been running instruments on my app. Its says i am leaking 864bytes & 624bytes from 2 NSCFString and the library responsible is Foundation.
So that leads me to believe thats its not a leak caused by me? Or is it?
Here is the offending method according to instruments. It seems to be a
substringWithRange
that is leaking.
-(void) loadDeckData
{
deckArray =[[NSMutableArray alloc] init];
NSString* path = [[NSBundle mainBundle] pathForResource:#"rugby" ofType:#"txt"
inDirectory:#""];
NSString* data = [NSString stringWithContentsOfFile:path encoding:
NSUTF8StringEncoding error: NULL];
NSString *newString = #"";
NSString *newline = #"\n";
NSString *comma = #",";
int commaCount = 0;
int rangeCount = 0;
NSString *nameHolder = #"";
NSString *infoHolder = #"";
NSMutableArray *statsHolder = [[NSMutableArray alloc] init];
for (int i=0; i<data.length; i++)
{
newString = [data substringWithRange:NSMakeRange(i, 1)];
if ([newString isEqualToString: comma]) //if we find a comma
{
if (commaCount == 0)// if it was the first comma we are parsing the
NAME
{
nameHolder = [data substringWithRange:NSMakeRange(i-
rangeCount, rangeCount)];
}
else if (commaCount == 1)//
{
infoHolder = [data substringWithRange:NSMakeRange(i-
rangeCount, rangeCount)];
//NSLog(infoHolder);
}
else // if we are on to 2nd,3rd,nth comma we are parsing stats
{
NSInteger theValue = [[data
substringWithRange:NSMakeRange(i-rangeCount,rangeCount)]
integerValue];
NSNumber* boxedValue = [NSNumber
numberWithInteger:theValue];
[statsHolder addObject:boxedValue];
}
rangeCount=0;
commaCount++;
}
else if ([newString isEqualToString: newline])
{
NSInteger theValue = [[data substringWithRange:NSMakeRange(i-
rangeCount,rangeCount)] integerValue];
NSNumber* boxedValue = [NSNumber numberWithInteger:theValue];
[statsHolder addObject:boxedValue];
commaCount=0;
rangeCount=0;
Card *myCard = [[Card alloc] init];
myCard.name = nameHolder;
myCard.information = infoHolder;
for (int x = 0; x < [statsHolder count]; x++)
{
[myCard.statsArray addObject:[statsHolder
objectAtIndex:x]];
}
[deckArray addObject:myCard];
[myCard autorelease];
[statsHolder removeAllObjects];
}
else
{
rangeCount++;
}
}
[statsHolder autorelease];
}
Thanks for your advice.
-Code
As Gary's comment suggests this is very difficult to diagnose based on your question.
It's almost certainly a leak caused by you however, I'm afraid.
If you go to the View menu you can open the Extended Detail. This should allow you to view a stack trace of exactly where the leak occurred. This should help diagnose the problem.
When to release deckArray? If deckArray is a class member variable and not nil, should it be released before allocate and initialize memory space?

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