NSString stringWithFormat swizzled to allow missing format numbered args - iphone

Based on this SO question asked a few hours ago, I have decided to implement a swizzled method that will allow me to take a formatted NSString as the format arg into stringWithFormat, and have it not break when omitting one of the numbered arg references (%1$#, %2$#)
I have it working, but this is the first copy, and seeing as this method is going to be potentially called hundreds of thousands of times per app run, I need to bounce this off of some experts to see if this method has any red flags, major performance hits, or optimizations
#define NUMARGS(...) (sizeof((int[]){__VA_ARGS__})/sizeof(int))
#implementation NSString (UAFormatOmissions)
+ (id)uaStringWithFormat:(NSString *)format, ... {
if (format != nil) {
va_list args;
va_start(args, format);
// $# is an ordered variable (%1$#, %2$#...)
if ([format rangeOfString:#"$#"].location == NSNotFound) {
//call apples method
NSString *s = [[[NSString alloc] initWithFormat:format arguments:args] autorelease];
va_end(args);
return s;
}
NSMutableArray *newArgs = [NSMutableArray arrayWithCapacity:NUMARGS(args)];
id arg = nil;
int i = 1;
while (arg = va_arg(args, id)) {
NSString *f = [NSString stringWithFormat:#"%%%d\$\#", i];
i++;
if ([format rangeOfString:f].location == NSNotFound) continue;
else [newArgs addObject:arg];
}
va_end(args);
char *newArgList = (char *)malloc(sizeof(id) * [newArgs count]);
[newArgs getObjects:(id *)newArgList];
NSString* result = [[[NSString alloc] initWithFormat:format arguments:newArgList] autorelease];
free(newArgList);
return result;
}
return nil;
}
The basic algorithm is:
search the format string for the %1$#, %2$# variables by searching for %#
if not found, call the normal stringWithFormat and return
else, loop over the args
if the format has a position variable (%i$#) for position i, add the arg to the new arg array
else, don't add the arg
take the new arg array, convert it back into a va_list, and call initWithFormat:arguments: to get the correct string.
The idea is that I would run all [NSString stringWithFormat:] calls through this method instead.
This might seem unnecessary to many, but click on to the referenced SO question (first line) to see examples of why I need to do this.
Ideas? Thoughts? Better implementations? Better Solutions?

Whoa there!
Instead of screwing with a core method that you very probably will introduce subtle bugs into, instead just turn on "Static Analyzer" in your project options, and it will run every build - if you get the arguments wrong it will issue a compiler warning for you.
I appreciate your desire to make the application more robust but I think it very likely that re-writing this method will more likely break your application than save it.

How about defining your own interim method instead of using format specifiers and stringWithFormat:? For example, you could define your own method replaceIndexPoints: to look for ($1) instead of %1$#. You would then format your string and insert translated replacements independently. This method could also take an array of strings, with NSNull or empty strings at the indexes that don't exist in the “untranslated” string.
Your method could look like this (if it were a category method for NSMutableString):
- (void) replaceIndexPointsWithStrings:(NSArray *) replacements
{
// 1. look for largest index in "self".
// 2. loop from the beginning to the largest index, replacing each
// index with corresponding string from replacements array.
}
Here's a few issues that I see with your current implementation (at a glance):
The __VA_ARGS__ thingy explained in the comments.
When you use while (arg = va_arg(args, id)), you are assuming that the arguments are nil terminated (such as for arrayWithObjects:), but with stringWithFormat: this is not a requirement.
I don't think you're required to escape the $ and # in your string format in your arg-loop.
I'm not sure this would work well if uaStringWithFormat: was passed something larger than a pointer (i.e. long long if pointers are 32-bit). This may only be an issue if your translations also require inserting unlocalised numbers of long long magnitude.

Related

Objective C: looping issue

I'm just starting out with objective c (coming from java) and I'm working on a calculator program just to practice with the syntax and some basic stuff. The way I'm going about it is having the user input a string and looking through for operators (taking order of operations into account) and then finding the term surrounding that operator, calculating it, replacing the term with the answer, and repeating for all the terms; however, I'm having an issue with the method I'm using to calculate the term. I pass in the index of the operator and have it loop backwards until it hits another operator to find the number immediately before it, and do the same forwards for the number after. My issue is that the loop does not stop when it hits the operators, and instead just continues until the end of the string in both directions. It's probably something really simple that I've overlooked but I've been trying to figure this out for a while and can' seem to get it. I've included an SSCCE of just the first half of the method, with a predetermined string and operator index. (also, a secondary question: is there any better way to post code blocks on this site rather than manually putting in 4 spaces before every line?)
#import <Foundation/Foundation.h>
int firstNumInTerm(int index);
NSString *calculation;
int main(int argc, const char * argv[])
{
#autoreleasepool {
calculation = #"51-43+378*32";
int firstNumber = firstNumInTerm(9);
NSLog(#"The number before the term is: %i", firstNumber);
}
return 0;
}
int firstNumInTerm(int index){
int firstNumIndex = index - 1;
int firstNumLength = 1;
NSRange prevChar = NSMakeRange(firstNumIndex - 1, 1);
while ([calculation substringWithRange:prevChar] != #"*" &&
[calculation substringWithRange:prevChar] != #"/" &&
[calculation substringWithRange:prevChar] != #"+" &&
[calculation substringWithRange:prevChar] != #"-" &&
firstNumIndex > 0) {
NSLog(#"prevChar: %#", [calculation substringWithRange:prevChar]);//TEST
firstNumIndex--; firstNumLength++;
prevChar = NSMakeRange(firstNumIndex - 1, 1);
}
NSRange firstRange = NSMakeRange(firstNumIndex, firstNumLength);
int firstNum = [[calculation substringWithRange:firstRange] intValue];
NSLog(#"firstNum String: %#", [calculation substringWithRange:firstRange]);//TEST
NSLog(#"firstNum int: %i", firstNum);//TEST
return firstNum;
}
The problem with this line:
[calculation substringWithRange:prevChar] != #"*" is that you are comparing the value of two pointers. [calculation substringWithRange:prevChar] returns a pointer to an NSString object, as does the NSString literal statement #"*". The simplest way to compare two strings is by using the isEqualToString: method of NSString. For example:
NSString *myName = #"Stephen";
NSString *yourName = #"Matt";
if([myName isEqualToString:yourName]){
printf("We have the same name!");
}
else{
printf("We do not have the same name");
}
If you are going to be doing a lot of string comparisons, it might be wise to write a macro, such as:
#define STREQ(x,y) [x isEqualToString:y]
Regarding copy/pasting code into StackOverflow:
Since I use XCode 99% of the time, I find it handy to select the text I am going to copy and then hit Cmd-]. This shifts the text to the right one tab-width. I then Cmd-c to copy and then Cmd-[ to undo the right-shift.
You can't do that in Objective-C: [calculation substringWithRange:prevChar] != #"*"
Instead, you need to do :
[[calculation substringWithRange:prevChar] compare:#"*"] != NSOrderedSame
(I know, it's longer, but arithmetic operators aren't overloaded for string like they are in Java).
I see others have answered this to correct the issue with your string comparison operations, but a better way to split this string up would be using NSString's native parsing methods. For example:
NSArray *numbers = [ calculation componentsSeparatedByCharactersInSet:
[ NSCharacterSet characterSetWithCharactersInString: #"*/+-" ] ];
Will give you an array containing each of the numbers (in order) in your string. You could come up with custom parsing routines, but using NSString's is going to likely be more straightforward and a lot less buggy. It will also be easier for someone else to read and understand.
while((![[calculation substringWithRange:prevChar] isEqualToString:#"*"]) && …){
}
or
NSArray *operators = #[#"+", #"-", #"*", #"/"];
while(![operators contains:[calculation substringWithRange:prevChar]])

iOS - libical / const char * - memory usage

I am using the libical library to parse the iCalendar format and read the information I need out of it. It is working absolutely fine so far, but there is one odd thing concerning ical.
This is my code:
icalcomponent *root = icalparser_parse_string([iCalData cStringUsingEncoding:NSUTF8StringEncoding]);
if (root)
{
icalcomponent *currentEvent = icalcomponent_get_first_component(root, ICAL_VEVENT_COMPONENT);
while (currentEvent)
{
while(currentProperty)
{
icalvalue *value = icalproperty_get_value(currentProperty);
char *icalString = icalvalue_as_ical_string_r(value); //seems to leak
NSString *currentValueAsString = [NSString stringWithCString:icalString
encoding:NSUTF8StringEncoding];
icalvalue_free(value);
//...
//import data
//...
icalString = nil;
currentValueAsString = nil;
icalproperty_free(currentProperty);
currentProperty = icalcomponent_get_next_property(currentEvent, ICAL_ANY_PROPERTY);
} //end while
} //end while
icalcomponent_free(currentEvent);
}
icalcomponent_free(root);
//...
I did use instruments to check my memory usage and were able to find out, that this line seems to leak:
char *icalString = icalvalue_as_ical_string_r(value); //seems to leak
If I'd copy and paste this line 5 or six times my memory usage would grow about 400kb and never get released anymore.
There is no free method for the icalvalue_as_ical_string_r method because it's returning a char *..
Any suggestions how to solve this issue? I would appreciate any help!
EDIT
Taking a look at the apple doc says the following:
To get a C string from a string object, you are recommended to use UTF8String. This returns a const char * using UTF8 string encoding.
const char *cString = [#"Hello, world" UTF8String];
The C string you receive is owned by a temporary object, and will become invalid when automatic deallocation takes place. If you want to get a permanent C string, you must create a buffer and copy the contents of the const char * returned by the method.
But how to release a char * string properly now if using arc?
I tried to add #autorelease {...} in front of my while-loop but without any effort. Still increasing memory usage...
Careful with the statement "no free method...because it's returning a char*"; that is never something you can just assume.
In the absence of documentation you can look at the source code of the library to see what it does; for example:
http://libical.sourcearchive.com/documentation/0.44-2/icalvalue_8c-source.html
Unfortunately this function can do a lot of different things. There are certainly some cases where calling free() on the returned buffer would be right but maybe that hasn't been ensured in every case.
I think it would be best to request a proper deallocation method from the maintainers of the library. They need to clean up their own mess; the icalvalue_as_ical_string_r() function has at least a dozen cases in a switch that might have different deallocation requirements.
icalvalue_as_ical_string_r returns a char * because it has done a malloc() for your result string. If your pointer is non-NULL, you have to free() it after use.

Problem in return value on objective-C

please look at this code:
-(NSString *) myfun:(NSString *)name paramnoone:(int)a paramnotwo:(int)b {
static int numberofcall=0;
if(a>b) {
return name;
}
NSString *secondname = [[NSString alloc]init];
secondname = [name StringByAppendingString:#"test"];
numberofcall++;
return secondname;
}
i have a problem on it, when my code is on "return secondname" next step is going to "return name" on if statement part, im confusing a lot , because c++ does not have this problem,
please help me on solve it,
thanks for ur help and sorry for my bad English.
(Until the question is explained further I can't really answer the question, but still have valuable infos which justify being posted as an answer, so here it goes.)
In the line:
NSString *secondname = [[NSString alloc]init];
You allocate an empty string. But in the very next line:
secondname = [name StringByAppendingString:#"test"];
You overwrite the pointer secondname to the previously allocated empty string, thus creating a memory leak. Since you do not use the empty string at all, remove the first line and turn the second line into:
NSString *secondname = [name StringByAppendingString:#"test"];
Edit: Based on comments to the questions, I think what you're asking is this (correct me if I'm wrong):
You are debugging the method.
While stepping through the method with the debugger, the flow proceeds normally through the method.
But after the numberofcall++; line, the debugger suddenly jumps to the return name; instead of the return secondname; line.
If that's what's happening to you: this is normal behavior, unfortunately. When the debugger reaches a return statement the marker always "jumps" to the first return statement in the method. But even though it doesn't look that way, your return secondname; statement is really executed.

String manipulation in objective-c

this is hard to describe but I am currently catching a string from a database, this string can be 1-4 characters long, however I am wanting to always display 4 characters, so if i get say a string back that is 34, i want it to be 0034.
I have set up a method to catch the string so now I just need to figure out how to do this. what I then plan to do is feed that string into a NSArray so I can send each [i'th] of the array off to 4 differetn methods that control animations in my app.
The reason its in string format is because I have had to bounce it round from hex, to int to string for various formatting reasons within the application.
this is my code i have so far. Suggestions/solutions would be great thankyou, I am so new its hard to find solutions for stuff like string manipulation etc..
//... other method I am getting the string from/.
[self formatMyNumber:dataString];
///..
-(void)formatMyNumber:(NSString *)numberString{
//resultLabel.text = numberString; //check to make sure string makes it to here.
//NSLog(#"hello From formatMyNumber method"); //check
}
//..
//the with send off each character to 4 animation methods that accept integers.
- (void)playAnimationToNumber:(int)number{
//...
//UpDated... weird stuff happening.
here is my method so far.
//Number Formatter
-(void)formatMyNumber:(NSString *)numberString{
NSLog(#"This is what is passed into the method%#",numberString);
int tempInt = (int)numberString;
NSLog(#"This is after I cast the string to an int %i",tempInt);
//[NSString alloc] stringWithFormat:#"%04d", numberString];
NSString *tempString = [[NSString alloc] initWithFormat:#"%04d", tempInt];
NSLog(#"This is after I try to put zeros infront %#",tempString);
//resultLabel.text = tempString;
//NSLog(#"hello From formatMyNumber method");
}
this is the output.
[Session started at 2011-06-19
16:18:45 +1200.] 2011-06-19
16:18:54.615 nissanCode0.1[4298:207]
731 2011-06-19 16:18:54.616
nissanCode0.1[4298:207] 79043536
2011-06-19 16:18:54.617
nissanCode0.1[4298:207] 79043536
2011-06-19 16:18:54.617
nissanCode0.1[4298:207] hello From
formatMyNumber method
As far as the number of zeros preceding your string goes there are a couple of ways to do this. I'd suggest:
NSString *myString = [NSString stringWithFormat:#"%04d",[dataString intValue]];
Is it possible you could have the number in integer form instead of string form? If so, it's pretty easy to use [NSString stringWithFormat:#"%04d", number]. See here for a list of the possible format specifiers.
See what stringWithFormat: can do. I realize you mentioned your numbers are NSStrings, but if they were ints, or you convert them back to ints, the following may do the trick. Modify the following to best suit your need:
return [NSString stringWithFormat:#"%04d", number];

how to define a returning NSString function in Objective-C / Xcode using a temporary variable?

I would like to define the following function in Objective-C. I have provided pseudo-code to help illustrate what I'm trying to do.
PSEUDOCODE:
function Foo(param) {
string temp;
if(param == 1) then
temp = "x";
else if(param == 2) then
temp = "y";
else if(param == 3) then
temp = "z";
else
temp = "default";
end if
return temp;
}
For some reason if I do this... the variable who I assign it to results in a "BAD Access" error.
I don't know what the difference between:
static NSstring *xx;
or the non-static:
NSString *xx;
declarations are, and how or why I would want to use one over the other.
I also do not fully understand the initializers of NSString, and how they differ. For example:
[[NSString alloc] initWithString:#"etc etc" ];
or the simple assignment:
var = #""
or even:
var = [NSString stringWithString:#"etc etc"];
Can you give me a hand please?
So far, using the NSString value returned from functions like those listed above, always causes an error.
static NSstring *xx;
That declares a statically allocated variable, much like it does in C.
NSstring *xx;
Inside a method that declares a normal local stack variable, just as it does in C.
As you should be aware, the difference between the two is that the first will keep its value between invocations of the function (and can cause trouble if the function is called from multiple threads).
[[NSString alloc] initWithString:#"etc etc"]
That creates a new NSString object, with the contents etc etc. This may or may not be the same as any other NSString object in your program with the same contents, but you don't have to care. Memory management wise, you own it, so you are responsible for ensuring that you eventually call release or autorelease on it to avoid leaking memory.
#"etc etc"
[NSString stringWithString:#"etc etc"]
Those are basically the same. Both give you an NSString object with the contents etc etc. This may or may not be the same as any other NSString object in your program with the same contents, but you don't have to care. Memory management wise, you do not own it, so you must not call release or autorelease on the object unless you first took ownership by calling retain. Also, since you do not own it, you can use it within your method, pass it as a parameter to other methods, and even use it as the return value from your method, but you may not store it in an ivar or static variable without taking ownership by calling retain or making a copy (with copy).
Also, note that "" and #"" are very different. The first gives you a const char * exactly as it does in C, while the second gives you an NSString object. Your program will crash if you use a const char * where the code expects an NSString object.
You can do it this way:
- (NSString *)functionName:(int)param {
NSString *result = nil;
switch (param) {
case 1:
result = [NSString stringWithString:#"x"];
break;
case 2:
result = [NSString stringWithString:#"y"];
break;
case 3:
result = [NSString stringWithString:#"z"];
break;
default:
result = [NSString stringWithString:#"defaultv"];
break;
}
return result;
}
Post real code, not pseudo code, as it makes it much easier to answer your question in concrete terms.
Given that you indicate that you are quite new to Objective-C, I would suggest starting with the language guide and then moving on to the memory management guide.