I am new to objective c. Trying to find out the type of NSString in Objective C. I use the sizeof() method from C and lengthOfBytesUsingEncoding method using UTF8 encoding from NSString.
NSString *test=@"a";
NSLog(@"LengthOfBytesUsingEncoding: %lu bytes", [test lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
printf("NSString: %lu\n", sizeof(test));
This is gonna give me in Console
LengthOfBytesUsingEncoding: 1 bytes and NSString: 8 bytes
What is the difference between the two results? Why LengthOfBytesUsingEncoding returns 1 bytes and sizeof method returns 8 bytes? What is the type of NSString? Int, float, long, long double?
CodePudding user response:
The length of bytes gives you the length of text content using the specified encoding. In this case the string contains a single character, which in UTF8 is encoded as 1 byte.
The sizeof
gives you the size of the variable's type, which, in this case is a pointer to NSString
. The size of all pointers on 64bit architectures is 8 bytes. It's essentially the size of memory address, where NSString
data is stored. sizeof
is not a method and it's not even a function. It's an operator. The result is known at compile-time.
In other words:
The actual string contents are stored in memory in a format that is opaque and shouldn't interest you.
On another place in memory, there is
NSString
data structure that contains a pointer to the contents. You can get the size of this structure usingsizeof(NSString)
(actually the size will differ depending on concreteNSString
subclass, e.g.NSMutableString
,NSPlaceholderString
etc).Your variable contains a pointer to
NSString
, that is, its size issizeof(NSString*)
, which is always 8 bytes.
sizeof
operator shouldn't interest you much in Objective-C, unless you are dealing with pointer arithmetics, which should be rather rare.