objective-c - Why can I assign values to pointers? - objective-c

I understand pointers work with addresses and not the data itself. This is why I need to use the address-of (&) operator below as I need to assign the address of num to the pointer and not the actual value of num (40).
int num = 40;
int *numPtr = #
Therefore i'm confused as to why I can do this.
NSString *str = #"hello";
I've created a pointer str but instead of giving it an address i'm able to assign it some data, a literal string.
I thought pointers could only hold memory addresses so why am I able to directly assign it some data?
For someone trying to get their head around pointers and objects this is very confusing.

No you are not assigning a literal string to it, # makes a NSString object with the string value hello.
In most C languages strings are just an array of char, where char is a primitive type like int like in your example.

There is a reason you put an # before string literals (when you want an NSString and not a C string) in objective-c
#"String" is basically equivalent to [NSString stringWithCString:"string"] which returns a pointer to an NSString object containing the value "string"
It is the same way 1 is a c type integer, but #1 is a NSNumber representing the value of 1. If you see an # it means "this is shorthand for creating an object". (#[] for NSArrays, #{} for NSDictionarys, #(), #123, #YES, #NO for NSNumbers, and #"" for NSString)

C does not have strings. Usually char arrays are used to represent them.
NSString *str = #"hello";
can be thought of as short hand (literal) for:
char charArray[] = "hello";
NSString *str = [[NSString alloc] initWithBytes:charArray length:sizeof(charArray) encoding:NSUTF8StringEncoding]; // disregard character encoding for this example
or
unichar bla[] = {'h', 'e', 'l', 'l', 'o'};
str = [[NSString alloc] initWithCharacters:bla length:sizeof(bla)];
So an object is created and thus you need a pointer.

Related

How to replace a char in an an char array? Xcode

i got the following char array in Objective-C (Xcode):
char *incomeMessage;
NSString *str = [[NSString alloc] initWithBytes:data.bytes length:data.length encoding:NSUTF8StringEncoding];
incomeMessage = [str UTF8String];
NSLog(#"%c", incomeMessage[0]);
NSLog(#"%c", incomeMessage[1]);
NSLog(#"%c", incomeMessage[2]);
NSLog(#"%c", incomeMessage[3]);
NSLog(#"%c", incomeMessage[4]);
NSLog(#"%c", incomeMessage[5]);
For example I get some results like this in console:
"3
2
6
1
8
4"
Now i want to replace the char in incomeMessage[2] by 4:
incomeMessage[2] = '4';
But then it gives me the error:
EXC_BAD_ACCESS
Do you have an idea, how to solve the problem?
According to the reference documentation, UTF8String returns a read-only (const char*) reference to the string data.
The reference material goes on to note:
This C string is a pointer to a structure inside the string object,
which may have a lifetime shorter than the string object and will
certainly not have a longer lifetime. Therefore, you should copy the C
string if it needs to be stored outside of the memory context in which
you use this property.
So I'd suggest following their advice and creating a copy of the array and then performing your modifications against that.
For example: http://ideone.com/mhjwZW
You might have better luck with something like:
NSString* str = [[NSString alloc] initWithBytes:data.bytes length:data.length encoding:NSUTF8StringEncoding];
char* incomeMessage = malloc([str lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
strcpy(incomeMessage, [str UTF8String]);
//now you can change things
incomeMessage[2] = '4';
//do this when you're done
free(incomeMessage);
Although, is there any particular reason why you want to use a C-string/character array as opposed to an NSMutableString? I think you might find replaceCharactersInRange:withString: a better approach generally. See also: stringByReplacingCharactersInRange:withString:.
i got the following char array in Objective-C (Xcode)
You don't, you know. All you have is a pointer. You have not set aside any actual memory; there is no array there.
incomeMessage = [str UTF8String];
All you've done in that line is repoint the pointer incomeMessage at your string's UTF8String. A string's UTF8String is immutable. Note this passage in the docs:
you should copy the C string if it needs to be stored outside of the memory context in which you use this property.
So basically, if you want to write into an array of char, your first task should be to make an array of char.

discussing functionality of id's stringValue function?

I got a NSMutableArray object with int values
and I can get a certain value via :
int *v0=[[[arrayObj objectAtIndex:0] intValue];
there is no problem.
But
I got a NSMutableArray object with NSString values
and I cannot get a certain value via :
NSString *v0=[[[arrayObj objectAtIndex:0] stringValue];
//raises error
I want to learn and understand exactly what stringValue for... and why this error occurs ?
NSString *v0=[arrayObj objectAtIndex:0];
works as expected.I asusme its some kind of pointer with null terminated so it can leech value.
Im not sure this line is also unicode/encoded string safe code.
in conclusion:
want to know the purpose of stringValue with some lines o code snippets
I got a NSMutableArray object with int values
That's not possible, Cocoa arrays always contain objects. You probably have an array of NSNumber objects that wrap the integers, like:
NSArray *arrayOfNumbers = #[#1, #2, #3];
NSNumber objects have an intValue method, so this works:
int value = [arrayOfNumbers[0] intValue];
On the other hand when you have an array of strings ...
NSArray *arrayOfStrings = #[#"1", #"2", #"3"];
... you want to access individual elements directly, without converting the string object to something else:
NSString *element = arrayOfStrings[0];
NSString objects do not understand the stringValue method:
[arrayOfStrings[0] stringValue]; // crash: does not recognize selector
Back at the beginning, our NSNumber objects from the first array do understand stringValue. You can use it to convert the number to a string:
NSString *intString = [arrayOfNumbers[0] stringValue];
To make the confusion perfect, NSString also understand the intValue message:
int value = [arrayOfStrings[0] intValue];
Here intValue means to try to convert the string to a plain C int value.
The error you will be getting (but failing to post with your question) will be Unknown selector sent to instance and this is because NSString doesn't have a stringValue method.
The approach you suggest is correct:
NSString *v0 = [arrayObj objectAtIndex:0];
EDIT (prompted by #Answerbot's answer):
The reason you are confused is that [NSString intValue] is used to convert the string value to an integer, as long as the string represents an integer (i.e. #"123"). However you don't need this for string as the object is already a string. It's therefore not provided.

NSString (or NSArray or something) to variable parameter list of C (char *) strings

Is there any easy way to convert an Objective-C holding class of NSStrings into parameters for a function accepting a variable list of char *? Specifically I have a function like:
-(void)someFunction:(NSSomething *) var
that I want to forward to a C function like
void someCFunction(char * var, ...)
Is there an easy way to go about this?
No, you can only do what you want if the number of arguments you're passing is known at compile time. If you just want to convert a single string, use the -UTF8String message:
// Example with two strings
NSString *str1 = ...;
NSString *str2 = ...;
someCFunction([str1 UTF8String], [str2 UTF8String]); // etc.
But if the number of strings will vary at runtime, you'll need to use a different API, if one is available. For example, if there's an API that took an array of strings, you could convert the Objective-C array into a C array:
// This function takes a variable number of strings. Note: in C/Objective-C
// (but not in C++/Objective-C++), it's not legal to convert 'char **' to
// 'char *const *', so you may sometimes need a cast to call this function
void someCFunction(const char *const *stringArray, int numStrings)
{
...
}
...
// Convert Objective-C array to C array
NSArray *objCArray = ...;
int numStrings = [objCArray count];
char **cStrArray = malloc(numStrings * sizeof(char*));
for (int i = 0; i < count; i++)
cStrArray[i] = [[objCArray objectAtIndex:i] UTF8String];
// Call the function; see comment above for note on cast
someCFunction((const char *const *)cStrArray, numStrings);
// Don't leak memory
free(cStrArray);
This would do the trick:
NSString *string = #"testing string"
const char * p1=[string UTF8String];
char * p2;
p2 = const_cast<char *>(p1);
Yes, this can be done, and is explained here:
How to create a NSString from a format string like #"xxx=%#, yyy=%#" and a NSArray of objects?
And here:
http://www.cocoawithlove.com/2009/05/variable-argument-lists-in-cocoa.html
With modifications for ARC here:
How to create a NSString from a format string like #"xxx=%#, yyy=%#" and a NSArray of objects?
Also, variable arguments are not statically or strongly typed, as the other poster seems to be suggesting. In fact, there is no clear indication in the callee of how many arguments you really have. Determining the number of arguments generally breaks down into having to either specify the number by an count parameter, using a null terminator, or inferring it from a format string a la (s)print* . This is frankly why the C (s)print* family of functions has been the source of many errors, now made much much safer by the XCode / Clang / GCC compiler that now warns.
As an aside, you can approach statically typed variable arguments in C++ by creating a template method that accepts an array of an unspecified size. This is generally considered bad form though as the compiler generates separate instances for each size of array seen by by the compiler (template bloat).

nsstring in objective c

i am a beginer in objective c.i found the following line in code and is not able to understand what it does it do, as storeselect has not been used anywhere in the code.
NSString *storeSelect=#"";
Objective-C builds on C language. In C, quotes are placed around string literals, i.e. "hello". To distinguish NSString and C strings (char pointers, char *), Objective-C uses # in front of strings, so #"" is simply empty NSString. If there was no #, it would be empty C string, e.g. char *myString = "hello world";.
storeSelect is the name of a variable whose type is NSString *, with the value assigned to #""
It's just assigning an empty string to a variable named storeSelect. The #"" is for constant strings.
NSString *storeSelect=#"Hello World";
is a shortcut of -
NSString *str = [NSString stringWithCString:"Hello World"];
as "stringWithCString" is convenience method it will be automatically adds autoreleased.

Easiest way to concatenate NSString and int

Is there a general purpose function in Objective-C that I can plug into my project to simplify concatenating NSStrings and ints?
[NSString stringWithFormat:#"THIS IS A STRING WITH AN INT: %d", myInt];
That's typically how I do it.
Both answers are correct. If you want to concatenate multiple strings and integers use NSMutableString's appendFormat.
NSMutableString* aString = [NSMutableString stringWithFormat:#"String with one int %d", myInt]; // does not need to be released. Needs to be retained if you need to keep use it after the current function.
[aString appendFormat:#"... now has another int: %d", myInt];
NSString *s =
[
[NSString alloc]
initWithFormat:#"Concatenate an int %d with a string %#",
12, #"My Concatenated String"
];
I know you're probably looking for a shorter answer, but this is what I would use.
string1,x , these are declared as a string object and integer variable respectively. and if you want to combine both the values and to append int values to a string object and to assign the result to a new string then do as follows.
NSString *string1=#"Hello";
int x=10;
NSString *string2=[string1 stringByAppendingFormat:#"%d ",x];
NSLog(#"string2 is %#",string2);
//NSLog(#"string2 is %#",string2); is used to check the string2 value at console ;
It seems the real answer is no - there is no easy and short way to concatenate NSStrings with Objective C - nothing similar to using the '+' operator in C# and Java.