I found a c function which I would like to use in my app. Unfortunately, my c knowledge is not great. The first section of code shows the original c code and the second my “translation” to objective c. I have 3 questions I would appreciate help with please:
- Is my translation of the variables from their c counterparts to their objective c counterparts valid? (I have had no compiler warnings)
- Is it acceptable to use the free () at the end or should this be done in another way in objective c
c code:
unsigned int i, j, diagonal, cost, s1len, s2len;
unsigned int *arr;
char *str1, *str2;
general code...
s1len = strlen(str1);
s2len = strlen(str2);
arr = (unsigned int *) malloc(sizeof(unsigned int) * j);
general code...
free(arr);
objective c code:
NSUInteger i, j, diagonal, cost, s1len, s2len;
NSUInteger *arr;
const char *str1 = [source cStringUsingEncoding:NSISOLatin1StringEncoding];
const char *str2 = [target cStringUsingEncoding:NSISOLatin1StringEncoding];
general code...
s1len = strlen(str1);
s2len = strlen(str2);
arr = (NSUInteger *) malloc(sizeof(NSUInteger) * j);
general code...
free(arr);
Objective-C is a strict superset of C, therefore you can use any C code without any modifications. I suggest either using the C code as is (as far as possible) or re-implementing the algorithm with objects in Objective-C.
NSString to char
What you need to provide, is a way to make convert Objective-C objects into C types, like NSString* to char*.
The conversion is correct, but you might want to use
-UTF8Stringto keep all chars intact, Latin-1 might lose some information. The disadvantage of utf-8 is, that you’re C code might not be able to correctly work with it.You’d better get the lengths using one of NSString’s methods instead of strlen, because it has linear running time and NSString’s methods could be constant.
int to NSInteger
There’s no reason to convert ints to NSIntegers. Apple has added this type for 64bit compatibility. NSInteger is typedef’d so that on 32bit platforms it needs 32bit and on 64bit platforms 64bit.
I’d try to change as little as possible of the C code. (Makes it easier to update it when the original gets updated.) So just leave the ints as they are.
Memory management
C’s memory management is more basic than Objective-C’s, but as you seem to know you use malloc and free, that just stays the same. Retain/release and the garbage collector are only useful for objects anyway.