how to append from NSMutableArray - iphone

i try to append from NSMutableArray but the below exception, actually first 2 loop its giving result but the 3rd loop giving this exception
2009-12-04 12:01:19.044 AppBuzz[14562:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSCFString appendString:]: nil argument'
2009-12-04 12:01:19.057 AppBuzz[14562:207] Stack: (
820145437,
837578260,
819694387,
819694291,
814894619,
814804961,
17445,
23977,
18651,
19281,
862009284,
9035,
861597328,
861596264,
861928960,
861926972,
861925524,
858687888,
819893547,
819891231,
861592584,
861585968,
8749,
8612
)
terminate called after throwing an instance of 'NSException'
my code as below
for (int i = 0; i < [student count]; i++)
{
if([student objectAtIndex:i] != NULL)
{
dic = [student objectAtIndex:i];
tempName = [dic objectForKey:#"NAME"];
tempAvgMark = [[dic objectForKey:#"AVG_MARK"] intValue];
[data appendString:#"{\"name\":\""];
[data appendString:tempName]; // here i'm having prob
[data appendString:#"\",\"avg_mark\":\""];
//[data appendString:tempAvgMark];
[data appendString:#"\"}"];
}
}
NSLOG(#"Result - %#",data);
can anyone help for
1) to append [data appendString:tempName];
2) to append int value ([data appendString:tempAvgMark]; ) into data
thanks

You're trying to append a nil, which is illegal. You can easily get around this by changing the line in question to the following:
[data appendString:(tempName == nil ? #"" : tempName)];
Or replace that empty string with whatever else you want. To append a non-string value, convert it to a string like this:
[data appendString:[NSString stringWithFormat:#"%i", tempAvgMark]];
If tempAvgMark is not an 'int', you'll have to change the %i. For example, for NSNumbers, use %# instead.

The object for the key #"NAME" in the dictionary has to be a string, and to append an int you can use [string appendFormat:#"%d", someInt].

It appears from this message: NSCFString appendString:]: nil argument' that one of the dictionary values is null

Related

NSInternalInconsistencyException reason: '-[__NSCFArray replaceObjectAtIndex:withObject:]: mutating method sent to immutable object'

could you please help me to solve the following error:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray replaceObjectAtIndex:withObject:]: mutating method sent to immutable object'
array_Info = [[NSMutableArray alloc] init];
array_Info = [dict_Temp objectForKey:#"Children"];
NSMutableArray *temp = [[NSMutableArray alloc] initWithArray:self.array_Info];
int ran, arrayIndexing = 0;
while ([temp count] != 0)
{
ran = arc4random();
if(ran < 0)
ran*=-1;
ran = ran % [temp count];
if([temp count] == 1)
ran = 0;
NSLog(#"%d %d",arrayIndexing,ran);
[self.array_Info replaceObjectAtIndex:arrayIndexing withObject:[temp objectAtIndex:ran]];
[temp removeObjectAtIndex:ran];
arrayIndexing++;
}
Presuming that array_Info is the backing variable for the self.array_Info property, you should change your second line to:
array_Info = [[dict_Temp objectForKey:#"Children"] mutableCopy];
This will give you the mutable array you need for the replaceObjectAtIndex:withObject: call.
It seems that self.array_Info is an immutable array. Make it mutable.

NSMutablearray define init issue

i have the following line of code
NSMutableArray *marray = [[NSArray arrayWithObjects: #"4", #"1", #"9", nil]mutableCopy];
and i want to replace it with the following line
NSMutableArray *marray = [[NSMutableArray alloc]initWithArray:garr];
where garr is global array from global method
the problem is that the code works fine when calling the first line but when using the second one the code crash , appreciate ur help and ideas thanks , iknow that the first one is NSArray but the garr variable source is NSMutable array
here is the code for garr
garr = [[NSMutableArray alloc]init];
for (int x = 0; x < 10; x++) {
[garr addObject:[NSNumber numberWithInt: arc4random()%200]];
here is the error msg
console error:2012-09-02 14:46:42.976 sort_alg[1561:207] -[NSCFNumber UTF8String]: unrecognized selector sent to instance 0x4b1a170 2012-09-02 14:46:42.978 sort_alg[1561:207] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFNumber UTF8String]: unrecognized selector sent to instance 0x4b1a170' * Call stack at first throw: –
this is the code that generates the end value
NSString *element;
NSEnumerator *iterator = [marray objectEnumerator];
while ((element = [iterator nextObject]) != nil)
printf("%s ", [element UTF8String]);
printf("\n");
[marray release]; // array needs to be released!
[pool release];
thanks
Problem lies in printf("%s ", [element UTF8String]);.
NSNumber has no UTF8String method, only a stringValue. You can't printf it either, but you can NSLog("%#", [element stringValue]), or NSLog("%d", [element intValue]) if you know it's an int.

application crashes when appendString for NSMutableString is used

I'm new to objective-c and I decided to start by working through Stanford's CS193s 2010F Session's lectures/assignments.
I was working on the second assignment, and I was stuck when I had to return a NSString that combines(concatenates) every strings inside NSMutableArray. (The MutableArray consists only NSString at its each indices)
My approach was to use a for loop to pass through the MutableArray's indicies(in the code below, the MutableArray is 'anExpression' with type 'id'). I declared a NSMutableString and added NSString at each indices of 'anExpression' array. Here is the code:
+ (NSString *)descriptionOfExpression:(id)anExpression{
NSMutableString *result = [NSMutableString string];
for (int i = 0;i<[anExpression count];i++){
[result appendString:[anExpression objectAtIndex:i]];
}
return result;
}
However, at
[result appendString:[anExpression objectAtIndex:i]];
xcode crashes with following error statements:
2012-07-17 01:44:51.014 Calculator[9470:f803] -[__NSCFNumber length]: unrecognized selector sent to instance 0x68732c0
2012-07-17 01:44:51.015 Calculator[9470:f803] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber length]: unrecognized selector sent to instance 0x68732c0'
*** First throw call stack:
(0x13ca022 0x155bcd6 0x13cbcbd 0x1330ed0 0x1330cb2 0x12d2d18 0x13460d7 0x1397a8d 0x3a50 0x27ed 0x13cbe99 0x1714e 0x170e6 0xbdade 0xbdfa7 0xbd266 0x3c3c0 0x3c5e6 0x22dc4 0x16634 0x12b4ef5 0x139e195 0x1302ff2 0x13018da 0x1300d84 0x1300c9b 0x12b37d8 0x12b388a 0x14626 0x1ed2 0x1e45 0x1)
terminate called throwing an exception
I looked through apple's developer's document, saw 'NSString stringWithFormat:' method, and decided to use this method instead:
+ (NSString *)descriptionOfExpression:(id)anExpression{
NSMutableString *result = [NSMutableString string];
for (int i = 0;i<[anExpression count];i++){
[result appendString:[NSString stringWithFormat:#"%#",[anExpression objectAtIndex:i]]];
}
return result;
}
and it works now.
now I'm confused why second code works but the first doesn't.
I thought appending string only fails(and crashes) when it's passed a nil...
Is there something I'm missing?
Thank you in advance :)
It looks like the contents of anExpression are instances of NSNumber instead of NSString. The error you are getting is a hint as to how appendString works; it's first step is obviously to ask the passed "string" how long it is (presumably so it can allocate enough memory). This is obviously not a method on NSNumber (hence the crash) and stringWithFormat is designed to do type-checking and be more flexible.
I suspect you could also use stringValue just as well:
[result appendString:[[anExpression objectAtIndex:i] stringValue]];
+ (NSString *)descriptionOfExpression:(id)anExpression{
NSMutableString *result = [NSMutableString string];
for (int i = 0;i<[anExpression count];i++) {
[result appendString:[[anExpression objectAtIndex:i] stringValue]];
}
return result;
}
Converting it into string would help you!!
Use this function:
+ (NSString *)descriptionOfExpression:(id)anExpression
{
NSMutableString *result = [[NSMutableString alloc] init];
for (int i = 0;i<[anExpression count];i++)
{
NSString *str = [NSString stringWithFormat:#"%#",[anExpression objectAtIndex:i]];
if(str)
{
[result appendString:str];
}
//OR
//[result appendFormat:[NSString stringWithFormat:#"%#",[anExpression objectAtIndex:i]]];
}
return result;
}

ObjectAtIndex causes app to crash

When I do an NSLog of the contents of my NSMutableArray, it returns :
(
hat,
hat
)
So why is it that when I do an NSLog like so NSLog(#"%#", [pro.matches objectAtIndex:0]); it crashes with the error: *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'
So strange
This is where I fill it:
[self.matches removeAllObjects];
NSArray *JSONarray = [[NSArray alloc] initWithArray:[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]];
int i;
for (i=0; i<[JSONarray count]; i++) {
//[self.matches addObject:[JSONarray objectAtIndex:i]];
[self.matches addObject:#"hat"];
}
//NSLog(#"boys with bo%#", [[matches objectAtIndex:1] objectForKey:#"host"]);
block();
//JSON and add to matches.
}
}];
block();
and this is where i call it:
[pro refreshMatchesWithCallback:^
{
//[self.tableView reloadData];
NSLog(#"the count of a lifetime is %#", [pro.matches objectAtIndex:0]);
}];
When you first log the contents it has nothing in due to the way completion blocks work, try this:
[pro refreshMatchesWithCallback:^
{
//[self.tableView reloadData];
if(pro.matches.count > 0) {
NSLog(#"the count of a lifetime is %#", [pro.matches objectAtIndex:0]);
}
}];
Hope this Helps!
Sam
always prefer to use this approach
for(Object* obj in arra)
{
...
}
this will enter in loop if the counter is greater than 0. no check needed
Cheerz :P

Splitting an NSString

I have the following code which fetches a string from an array of strings and splits the string into 2 parts.
NSString *temp = [tableViewData objectAtIndex:indexPath.row];
NSArray *tempArray = [temp componentsSeparatedByString: #"_"];
cell.textLabel.text = [tempArray objectAtIndex:1];
and the String which is added is as follows
newTitle = [NSString stringWithFormat:#"%d_%#",[Daily_QuoteViewController counter],title];
[plistArray addObject:newTitle];
[plistArray writeToFile:filepath atomically: YES];
Which is adding an index and a string.
I am trying to then split that string in the first code section. but trying to access the second part of the string at index 1 gives an out of bounds error.
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSArray objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
What is the best way to split the string in order to use both parts of the string
split firstPart_secondPart
Thanks in advance.
This seems fine to me. Can you print out NSString temp? NSLog(#"%#", temp);