Objective-C: How to create a method that will return a UInt8 array from int

I need to create an Objective-C method that converts an int to an array of bytes. In this case, I cannot use NSArray as the return type, it must be an UInt8 array. I wrote an easy way to do this, but it has errors at compile time and tells me that I have incompatible return types. Here is a snippet of code. Any ideas?

- (UInt8[])ConvertToBytes:(int) i { UInt8 *retVal[4]; retVal[0] = i >> 24; retVal[1] = i >> 16; retVal[2] = i >> 8; retVal[3] = i >> 0; return retVal; } 
+4
source share
2 answers

You cannot return the local array C. You need malloc(sizeof(UInt8) * 4) , fill it in, return the pointer, and, of course, remember to free it when you are done.

Here is an example of how it will be written and used (just to emphasize the importance of freeing allocated memory):

 + (UInt8 *)convertToBytes:(int)i { UInt8 *retVal = malloc(sizeof(UInt8) * 4); retVal[0] = i >> 24; retVal[1] = i >> 16; retVal[2] = i >> 8; retVal[3] = i >> 0; return retVal; } - (void)someMethodUsingTheOtherOne { int something = 900; UInt8 *bytesOfInt = [[self class] convertToBytes:something]; someFunctionUsingTheBytes(bytesOFInt); free(bytesOfInt); } 

(You will probably notice that I also changed it as a class method. Since it does not depend on any instance attributes, it is more reasonable for it to use a class method or even a function. But this has nothing to do with how arrays work and pointers - I just like to use a good coding style in the examples.)

+5
source

Returns the value in a struct . You cannot return C-style arrays from C functions, and this also means that you also cannot return them from Objective-C methods. You can return a structure, although structs also allow arrays as members.

 // in a header typedef struct { UInt8 val[4]; } FourBytes; // in source - (FourBytes) convertToBytes:(int) i { FourBytes result = { i >> 24, i >> 16, i >> 8, i }; return result; } - (void) someMethod { FourBytes test = [someObject convertToBytes:0x12345678]; NSLog ("%d, %d, %d, %d", test.val[0], test.val[1], test.val[2], test.val[3]); } 
+11
source

Source: https://habr.com/ru/post/1304209/


All Articles