Home > Mobile >  What type is NSString and how many bytes?
What type is NSString and how many bytes?

Time:10-24

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:

  1. The actual string contents are stored in memory in a format that is opaque and shouldn't interest you.

  2. 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 using sizeof(NSString) (actually the size will differ depending on concrete NSString subclass, e.g. NSMutableString, NSPlaceholderString etc).

  3. Your variable contains a pointer to NSString, that is, its size is sizeof(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.

  • Related