Reputation: 1024
i'm working with this method
-(void)fetchDataFromTLE:(const char *)line1 AndLine2:(const char *)line2{
writing this, the code works
char *line1= "blablabla";
char *lin2= "blebleble";
[self fetchDataFromTLE:line1 AndLine2:line2];
it works.
But i need to take line1 and line2 from an NSUserDefaults, saved as NSString.
So:
NSString *line1 = [[NSUserDefaults standardUserDefaults] objectforkey:@"line1"];
NSString *line2 = [[NSUserDefaults standardUserDefaults] objectforkey:@"line2"];
and, of course, if i try to call my method
[self fetchDataFromTLE:line1 AndLine2:line2];
it doesn't works
passing argument 1 of 'fetchDataFromTLE:AndLine2:' from incompatible pointer type
passing argument 2 of 'fetchDataFromTLE:AndLine2:' from incompatible pointer type
and that's normal. So i was thinking to cast my NSString* into a char*, but i found only one way to cast an NSString* into a const char*.
const char *AAA1 = [line1 UTF8String];
the cast is correct, but if a call my method i have this error
warning: passing argument 1 of 'fetchDataFromTLE:AndLine2:' discards qualifiers from pointer target type
So i thinked to cast che const char* into a char*... and the only way that i know is using strcpy.
so:
#include <stdio.h>
#include <string.h>
...
char *a;
strcpy(a, AAA1);
doesn't works because the app crashes!
What can i do?
Thanks!
Upvotes: 0
Views: 3958
Reputation: 57179
Since you are using objective-c why not take an NSString
as a parameter and then do the conversion inside the function. That would make your code a lot easier to use when needing to call the method.
-(void)fetchDataFromTLE:(NSString*)line1 AndLine2:(NSString*)line2
{
const char *szLine1 = [line1 UTF8String];
const char *szLine2 = [line2 UTF8String];
...
//Use the the char * only within the method
}
Your code will then look like the following
[self fetchDataFromTLE:[[NSUserDefaults standardUserDefaults] objectforkey:@"line1"]
AndLine2:[[NSUserDefaults standardUserDefaults] objectforkey:@"line2"]];
Upvotes: 4
Reputation: 7982
Your app crashes when you do your strcpy because you haven't allocated a.
char *a; //This doesn't actually point to anything
strcpy(a, AAA1);
What you want to do is this:
char *a = (char*)malloc(strlen(AAA1)+1);
strcpy(a, AAA1);
//perform your operations using a...
free(a);
I would suggest adapting your function, if possible, since you're working in objective-c, you should work with objective-c objects (NSString*).
Upvotes: 1
Reputation: 53960
You're right, you cannot cast a NSString to a primitive type, as NSString is an object.
You can safely cast the result of UTF8String
to a char *
, as long as you're sure that the function you call won't modify the value pointed by the pointer. Otherwise, you'll experience problem with your NSString object.
If you need to modify the pointer, then allocate another, and use strcpy.
Upvotes: 1