Casting in objective-c - iphone

I have a dictionary object that I am pulling data out of. The field is supposed to be a string field but sometime all that it contains is a number. I get the info using:
NSString *post = [[temp objectAtIndex:i] valueForKey:#"POSTDESCRIPTION"];
So it is going into a string object. However, when I try to assign that to a cell's text via:
cell.textLabel.text = post;
I get a the following error:
'NSInvalidArgumentException', reason: '*** -[NSDecimalNumber isEqualToString:]: unrecognized selector sent to instance 0x4106a80'
2009-10-20 13:33:46.563
I have tried casting it with the following ways to no avail:
NSString *post = [[[temp objectAtIndex:i] valueForKey:#"POSTDESCRIPTION"] stringValue];
NSString *post = (NSString *)[[temp objectAtIndex:i] valueForKey:#"POSTDESCRIPTION"];
cell.textLabel.text = [post stringValue];
cell.textLabel.text = (NSSting *)post;
What am I doing wrong?

Your dictionary doesn't contain an NSString. If you'd like the string representation of the object, you could call the object's description selector, e.g.:
NSString *post = [[[temp objectAtIndex:i] valueForKey:#"POSTDESCRIPTION"] description];

terry, jason and the other answers & comments are correct. what you're attempting would be like trying to cast an apple into an orange.
conveniently, NSNumber does have a stringValue method. so try this:
NSString *post = [[[temp objectAtIndex:i] valueForKey:#"POSTDESCRIPTION"] stringValue];
only do this if you know for sure it'll always be an NSNumber.
otherwise, you can try the rather hacky and inelligant:
NSString *post = [NSString stringWithFormat:#"%#",[[[temp objectAtIndex:i] valueForKey:#"POSTDESCRIPTION"] description];

Related

Memory management in appending a string?

I have an iPhone application in which i am creating an array in the didfinishlaunch in the appdelegate. Like this:
for(int i=1;i<53;i++)
{
NSString *namestring=[NSString stringWithString:#"avatar"];
NSString *string = [NSString stringWithFormat:#"%d",i];
NSString *pngstring=[NSString stringWithString:#".png"];
string = [string stringByAppendingString:pngstring];
namestring = [namestring stringByAppendingString:string];
NSLog(#"%#",namestring);
[avtararray addObject:namestring];
}
working fine.and everywhere i am doing the avatar job with my avatararray in the appdelegate.But in one case when i pop back to the previous view and try to load the string from the array again
NSString *avatarstringt=[[appDelegate.avtararray objectAtIndex:i]description];here it is crashing with a an error
-[CFString description]: message sent to deallocated instance..
when doing the profile job i know that the leak is in the above loop in the appendingstring code.Can anybody help me to remove this?
First of all, Never do this
NSString *string = [NSString stringWithFormat:#"%d",i];
NSString *pngstring=[NSString stringWithString:#".png"];
string = [string stringByAppendingString:pngstring];
The following statements, are redundant
NSString *namestring=[NSString stringWithString:#"avatar"];
NSString *pngstring=[NSString stringWithString:#".png"];
and should be written as:
NSString *namestring=#"avatar";
NSString *pngstring=#".png";
You can use as :
NSString *namestring=#"avatar";
NSString *numberString = [NSString stringWithFormat:#"%d",i];
NSString *pngstring=#"png";
namestring = [namestring stringByAppendingFormat:#"%#.%#",numberString,pngstring];
Even the shortest of code :
for(NSInteger i=1;i<5;i++){
NSString *namestring = [NSString stringWithFormat:#"avatar%#.png",#(i)];
NSLog(#"%#",namestring);
}
As suggested by rmaddy: you can use i as integer, no need of converting it into nsnumber
NSString *namestring = [NSString stringWithFormat:#"avatar%d.png",i];

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

combining 2 strings in objective-c

I have a problem when I try to combine 2 NSString
I extract 2 NSSring form a JSON and its diagrams are:
thumbList: ( "picture1.jpg", "picture2.jpg", "picture3.jpg" ... )
fullnameList: ("name1", "name2" , "name3" ... )
My intention is unite them into one using the following scheme:
("name1", "picture1.jpg", "name2", "picture2.jpg", "name3", "picture3.jpg"...)
NSArray *array_webdata=[[NSArray array] init];
NSString *searchStatus = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
array_webdata = [parsedata objectWithString:searchStatus error:nil];
//String with all data of each user
NSString *usersList = [array_webdata valueForKey:#"results"];
NSLog(#"\n results? = %# \n", usersList);
//String with thumbs
NSString *thumbList = [usersList valueForKey:#"thumb"];
NSLog(#"\n thumbs? = %# \n", thumbList);
//String with usernames
NSString *fullnameList = [usersList valueForKey:#"fullname"];
NSLog(#"\n fullnames? = %# \n", fullnameList);
NSMutableIndexSet *indexes = [NSMutableIndexSet indexSetWithIndex:1];
[indexes addIndex:3];
[fullnameList insertObjects:thumbList atIndexes:indexes];
NSLog(#"array: %#", fullnameList);
But when I try to execute shows the next error message: [__NSArrayI insertObjects:atIndexes:]: unrecognized selector sent to instance.
Can anyone help me?
You should use
NSMutableDictionary* dataDict = [NSMutableDictionary dictionaryWithObjects:picturesList forKeys:namesList];
// Whenever key needed for fetching record from Dictionary just write
NSArray* keyArr = [dataDict AllKey];
Now you have all key and you can fetch record with the help of above key.
All "unrecognized selector sent to instance." errors mean the same: you think some object has a method, but it really don't have it at runtime.
Due to the dynamic nature of Objective-C, if you're not sure of some object having a method you should always test it calling respondsToSelector: like this:
if ([myObj respondsToSelector:#selector(someMethod)]) {
[myObj someMethod];
}
In this case,
NSString *fullnameList = [usersList valueForKey:#"fullname"];
is a NSString. That class does not have a insertObjects:atIndexes: method. Maybe you have to declare it as an NSMutableArray

NSRegularExpression to extract text

All,
I have a dictionary with two keys and values. I need to extract bits and pieces from them and place them into seperate strings.
{
IP = "192.168.17.1";
desc = "VUWI-VUWI-ABC_Dry_Cleaning-R12-01";
}
That is what the dictionary looks like when I call description.
I want the new output to be like this:
NSString *IP = #"192.168.17.1";
NSString *desc = #"ABC Dry Cleaning"; //note: I need to get rid of the underscores
NSString *type = #"R";
NSString *num = #"12";
NSString *ident = #"01";
How would I achieve this?
I've read through the Apple developer docs on NSRegularExpression but I find it hard to understand. I'm sure once I get some help once here I can figure it out in the future, I just need to get started.
Thanks in advance.
Okay, so first, you have to get the object associated with each key:
NSString *ip = [dic objectForKey:#"IP"]; //Btw, you shouldn't start a variable's name with a capital letter.
NSString *tempDesc = [dic objectForKey:#"desc"];
Then, what I would do is split the string in tempDesc, based on the character -.
NSArray *tmpArray = [tempDesc componentsSeparatedByString:#"-"];
Then you just have to get the strings or substrings you're interested in, and reformat them as needed:
NSString *desc = [[tmpArray objectAtIndex:2] stringByReplacingOccurrencesOfString:#"_" withString:#" "];
NSString *type = [[tmpArray objectAtIndex:3] substringToIndex:1];
NSString *num = [[tmpArray objectAtIndex:3] substringFromIndex:1];
NSString *ident = [tmpArray objectAtIndex:4];
As you can see, this works perfectly without using NSRegularExpression.

obj-c problem setting array with componentsSeperatedByString

I have a data source with about 2000 lines that look like the following:
6712,Anaktuvuk Pass Airport,Anaktuvuk Pass,United States,AKP,PAKP,68.1336,-151.743,2103,-9,A
What I am interested in is the 6th section of this string so I want to turn it into an array, then i want to check the 6th section [5] for an occurrance of that string "PAKP"
Code:
NSBundle *bundle = [NSBundle mainBundle];
NSString *airportsPath = [bundle pathForResource:#"airports" ofType:#"dat"];
NSData *data = [NSData dataWithContentsOfFile:airportsPath];
NSString *dataString = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
NSArray *dataArray = [dataString componentsSeparatedByString:#"\n"];
NSRange locationOfAirport;
NSString *workingString = [[NSString alloc]initWithFormat:#""];
NSString *searchedAirport = [[NSString alloc]initWithFormat:#""];
NSString *airportData = [[NSString alloc]initWithFormat:#""];
int d;
for (d=0; d < [dataArray count]; d=d+1) {
workingString = [dataArray objectAtIndex:d];
testTextBox = workingString; //works correctly
NSArray *workingArray = [workingString componentsSeparatedByString:#","];
testTextBox2 = [workingArray objectAtIndex: 0]; //correctly displays the first section "6712"
testTextBox3 = [workingArray objectAtIndex:1] //throws exception index beyond bounds
locationOfAirport = [[workingArray objectAtIndex:5] rangeOfString:#"PAKP"];
}
the problem is that when the workingArray populates, it only populates with a single object (the first component of the string which is "6712". If i have it display the workingString, it correctly displays the entire string, but for some reason, it isn't correctly making the array using the commas.
i tried it without using the data file and it worked fine, so the problem comes from how I am importing the data.
ideas?
You code works. You should run it with the debugger to see what's happening. At a guess, your input data isn't what you think it is - possibly a different encoding, or different line endings.
See sample:
NSString *dataString = #"6712,Anaktuvuk Pass Airport,Anaktuvuk Pass,United States,AKP,PAKP,68.1336,-151.743,2103,-9,A";
NSArray *dataArray = [dataString componentsSeparatedByString:#"\n"];
for (NSString *workingString in dataArray) {
NSString *testTextBox = workingString; //works correctly
NSArray *workingArray = [workingString componentsSeparatedByString:#","];
NSString *testTextBox2 = [workingArray objectAtIndex: 0]; //correctly displays the first section "6712"
NSString *testTextBox3 = [workingArray objectAtIndex:1]; //throws exception index beyond bounds
NSRange locationOfAirport = [[workingArray objectAtIndex:5] rangeOfString:#"PAKP"];
}
there was a problem in the data where there were a few "\"s that caused the errors.