Sending __string to __unsafe_unretained changes retain/release properties of pointer - objective-c

Following is a code segment which I learnt in a lynda iOS training course based on iOS 4 (without ARC).
I was going to implement the same code in my Xcode 4.2 which has ARC turned on with the iOS 5 SDK. It gave me this error:
error: Semantic Issue: Sending '__strong id *' to parameter of type '__unsafe_unretained id **' changes retain/release properties of pointer"
- (NSNumber *) insertRow:(NSDictionary *) record {
// NSLog(#"%s", __FUNCTION__);
int dictSize = [record count];
// the values array is used as the argument list for bindSQL
id keys[dictSize]; // not used, just a side-effect of getObjects:andKeys
id values[dictSize];
[record getObjects:values andKeys:keys]; // convenient for the C array
// construct the query
NSMutableArray * placeHoldersArray = [NSMutableArray arrayWithCapacity:dictSize];
for (int i = 0; i < dictSize; i++) // array of ? markers for placeholders in query
[placeHoldersArray addObject: [NSString stringWithString:#"?"]];
NSString * query = [NSString stringWithFormat:#"insert into %# (%#) values (%#)",
tableName,
[[record allKeys] componentsJoinedByString:#","],
[placeHoldersArray componentsJoinedByString:#","]];
[self bindSQL:[query UTF8String] arguments:(va_list)values];
sqlite3_step(statement);
if(sqlite3_finalize(statement) == SQLITE_OK) {
return [self lastInsertId];
} else {
NSLog(#"doQuery: sqlite3_finalize failed (%s)", sqlite3_errmsg(database));
return [NSNumber numberWithInt:0];
}
}
** The real case came with the following segment of this whole function.**
int dictSize = [record count];
// the values array is used as the argument list for bindSQL
id keys[dictSize]; // not used, just a side-effect of getObjects:andKeys
id values[dictSize];
[record getObjects:values andKeys:keys]; // convenient for the C array
How can I resolve this?

There's a lot wrong with that function. The fix for your compiler error is simply to declare keys and values with the __unsafe_unretained ownership qualifier:
__unsafe_unretained id keys[dictSize]; // not used, just a side-effect of getObjects:andKeys
__unsafe_unretained id values[dictSize];
However, the cast (va_list)values is undefined behavior. Don't do it.
Since you're not using the keys array at all, it would be better to do something like this:
- (NSNumber *) insertRow:(NSDictionary *) record {
int count = [record count];
NSMutableArray * placeHoldersArray = [NSMutableArray arrayWithCapacity:count];
for (int i = 0; i < count; i++) {
[placeHoldersArray addObject: #"?"];
}
NSString * query = [NSString stringWithFormat:#"insert into %# (%#) values (%#)",
tableName,
[[record allKeys] componentsJoinedByString:#","],
[placeHoldersArray componentsJoinedByString:#","]];
[self bindSQL:[query UTF8String] arguments:[record allValues]];
sqlite3_step(statement);
if(sqlite3_finalize(statement) == SQLITE_OK) {
return [self lastInsertId];
} else {
NSLog(#"doQuery: sqlite3_finalize failed (%s)", sqlite3_errmsg(database));
return [NSNumber numberWithInt:0];
}
}
And then modify bindSQL:arguments: to take an NSArray * instead of a va_list. If you need help doing that, show us the source code of bindSQL:arguments:.
(However, I don't think it's documented that allKeys and allValues return parallel arrays…)

Edited for const char pointer:
- (NSNumber *) insertRow:(NSDictionary *) record {
NSArray * placeHoldersArray = [NSArray array];
const char * cStrings[record.count];
NSArray * keys = [record allKeys];
NSUInteger i=0;
for (id key in keys) {
id object = [record objectForKey:key];
if ([object isKindOfClass:[NSString class]])
cStrings[i++] = [(NSString*)object UTF8String];
else
#throw [NSException exceptionWithName:NSInvalidArgumentException reason:#"Expected NSString" userInfo:nil];
placeHoldersArray = [placeHoldersArray arrayByAddingObject: #"?"];
}
NSString * query = [NSString stringWithFormat:#"insert into %# (%#) values (%#)",
tableName,
[keys componentsJoinedByString:#","],
[placeHoldersArray componentsJoinedByString:#","]];
[self bindSQL:[query UTF8String] arguments:(va_list)cStrings];
sqlite3_step(statement);
if(sqlite3_finalize(statement) == SQLITE_OK) {
return [self lastInsertId];
} else {
NSLog(#"doQuery: sqlite3_finalize failed (%s)", sqlite3_errmsg(database));
return [NSNumber numberWithInt:0];
}
}
In the update method, you should understand that a va_list is just a group of any number of arguments. It is assumed that the method that is called knows how to determine the type. An example of this is with NSLog. It uses the format string to determine the type of an unknown number of variables, which are passed in as a va_list, i.e. comma separated values. Because you only have one value, just pass in the value. I am sketchy on whether sqlite wants a c string or if it will take an integer in this case.

Related

Browsing an object's fields

In Objective C, I have an object e.g. Person with a lot of fields firstName, lastName, phoneNumber, address, city... and so on. These fields types are NSString and any of these could be nil.
Now I want to concatenate my field values in another NSString :
Person *p = ...
NSMutableString *s = [[NSMutableString alloc] init];
for (NSString *field in #[p.firstName, p.lastName, p.phoneNumber,
p.adress, p.city, ....more fields...]) {
if ([field length] > 0) {
[s appendFormat:#"%#\n", field];
}
}
Issue is that this code crash whenever one of the field is nil. I have the exception :
[__NSPlaceholderArray initWithObjects:count:]: attempt to insert nil object
from objects[0]'
How could I handle simply the case of nil values within my for loop ?
I agree with #TomPace's post, for this small number I would do a simple if/else.
However, there may be times you do need to loop through a list of fields.
It's a bad idea to blindly pull the values into an array as you could be trying inserting nil values into the array. In this case, it would be better to place the field names into a key array as strings and loop through the list using valueForKey: to access the values. I would possibly store the keys list somewhere else where it can be used again.
Person *p = ...
NSMutableString *s = [[NSMutableString alloc] init];
NSArray *keys = #[#"firstName", #"lastName", #"phoneNumber", #"adress", #"city"];
for (NSString *key in keys)
{
NSString *value = [p valueForKey:key];
if ([value length] > 0) {
[s appendFormat:#"%#\n", value];
}
}
Person *person = [[Person alloc] init];
person.firstName = nil;
person.lastName = #"lastName";
NSMutableString *s = [[NSMutableString alloc] init];
[s appendFormat:#"%#\n", person.firstName == nil?#"":person.firstName];
[s appendFormat:#"%#\n", person.lastName == nil?#"":person.lastName];
For a selection of fields this small, don't use a for loop.
You may be saving a bit of code by attempting the for-loop structure, but it's really not the way to go if you're building the NSArray with only a few fields, and especially because you can't put nil items in it.
A better way to go is:
Person *p = ...
NSMutableString *s = [[NSMutableString alloc] init];
if ([p.firstName length] > 0) [s appendFormat:#"%#\n", p.firstName];
if ([p.lastName length] > 0) [s appendFormat:#"%#\n", p.lastName];
if ([p.phoneNumber length] > 0) [s appendFormat:#"%#\n", p.phoneNumber];
if ([p.adress length] > 0) [s appendFormat:#"%#\n", p.adress];
if ([p.city length] > 0) [s appendFormat:#"%#\n", p.city];
Edit, after original Question was updated with large amount of fields.
Like #BergQuester said, an approach to support a larger, arbitrary set of fields is using KVO-style inspection.
NSArray *fieldNames = #[#"firstName", #"lastName", #"phoneNumber", ....more fields...];
NSString *field;
for (NSString *fieldName in fieldNames) {
field = [p valueForKey:fieldName];
if ([field length] > 0 ) {
[s appendFormat: #"%#\n", field];
}
}
Try to create NSMutableString category
#import "NSMutableString+checkForNilObject.h"
#implementation NSMutableString (checkForNilObject)
-(void) appendNotNillObject:(NSString *) string
{
if(string)
{
[self appendString:string];
}
}
#end
You can override the getters of the class Person.
#implementation Person
- (NSString *)firstName{
if (_firseName == nil)
_firstName = #"";
return _firstName;
}
///....Other setters
#end
Like this you can define all your setters here.

Difficulty with getting random words from NSArray

When I Build & Run my application, it will not generate anything. What I have generating are words and after it erases that word and continues until it exhausts all the words and then repopulates the list again. Here is the code:
#implementation randomnumbersViewController
#synthesize words;
#synthesize randomArray;
#synthesize array;
-(IBAction)generateNumber:(id)sender {
NSInteger randomize(id num1, id num2, void *context);
int rand = arc4random() %2;
if (rand)
return NSOrderedAscending;
else
return NSOrderedDescending;
}
- (void)resetRandomArray;
{
[randomArray setArray: array];
[randomArray sortUsingFunction:random context:NULL];
}
- (NSString*) getRandomWord; {
if ([randomArray count] ==0)
return nil;
NSString* result;
NSInteger randomIndex = [[randomArray lastObject] intValue];
[randomArray removeLastObject];
result = [words objectAtIndex:randomIndex];
return result;
}
- (void)buildRandomWordArray
{
NSInteger index;
NSError *theError;
NSString *path = [[NSBundle mainBundle] pathForResource:#"words" ofType:#"text"];
NSString *text = [NSString stringWithContentsOfFile: path
encoding: NSUTF8StringEncoding
error: &theError];
self.words = [text componentsSeparatedByString: #"\n"];
int arraySize = [words count];
self.array = [NSMutableArray arrayWithCapacity:arraySize];
//This code fills "array' with index values from 0 to the number of elements in the "words" array.
for (index = 0; index<arraySize; index++)
[array addObject: [NSNumber numberWithInt: index]];
[self resetRandomArray];
//for (index = 0; index<=arraySize; index++)
// NSLog(# "Random word: %#", [self getRandomWord]);
}
Also a .txt document must be included in the resources folder in for this to work and I do have it there, but nothing. Does anyone have any suggestions as to how I can actually get it to generate the words, or why it isn't working properly?
I don't get how sorting the array ascending or descending is going to shuffle the array, maybe because it doesn't. :) You should use the Fisher–Yates shuffle implemented here: What's the Best Way to Shuffle an NSMutableArray? Import that category, and just call shuffle on the mutable array.

Find number of objects in NSMutableArray

I have a problem with counting numbers of object in nsmutablearray. I have this code:
- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath
{
NSUInteger numObjects = [selected count];// selected is nsmutablearray
for ( int i = 0; i<numObjects; i++)
{
NSLog(#"%# == %# , nr.object =%#",[AnotherArray objectAtIndex:indexPath.row], [selektuara objectAtIndex:i], numObjects); // here stops the by reporting this: Program recived signal: "EXC_BAD_ACCESS"
if ([selected objectAtIndex:i] == [AnotherArray objectAtIndex:indexPath.row])
{
NSLog(#"%#",[selected objectAtIndex:i]);
return UITableViewCellAccessoryCheckmark;
}
else
{
return UITableViewCellAccessoryNone;
}
}
}
When i remove NSLog for numbers of object, it counts only one object and compare only that.
So has anyone else another solution how to get this number?
Thanks.
Error in using NSLog:
NSLog(#"%# == %# , nr.object =%d",[AnotherArray objectAtIndex:indexPath.row], [selektuara objectAtIndex:i], numObjects);
As numObjects is NSUInteger you should use %d to print its value.
Error in comparing:
if ([[selected objectAtIndex:i] compare:[AnotherArray objectAtIndex:indexPath.row]] == NSOrderedSame)
You shouldn't use == for comparing objects in Objective-C
You must not try to output an unsigned integer with the %# format specifier. Use %u instead.

Read SQLite problem

I have NSTableView with two columns, and i wanna fill them entries from SQLite database.
this method is make query for table
-(void)getPersons
{
NSString *file = [[NSBundle mainBundle] pathForResource:#"persons" ofType:#"db"];
sqlite3 *database = NULL;
if (sqlite3_open([file UTF8String], &database)==SQLITE_OK)
{
NSLog(#"i open database");
sqlite3_exec(database, "select name,age from persons", MyCallback, persons, NULL);
}
sqlite3_close(database);
}
the problem appers in MyCallback method:
static int MyCallback(void *context, int count, char **values, char **columns)
{
NSMutableArray *persons = (NSMutableArray *)context;
for (int i=0; i < count; i++) {
NSString *columnname = [NSString stringWithUTF8String:columns[i]];
const char *nameCString = values[i];
if ([columnname isEqualTo:#"name"]) {
[persons addObject:[NSString stringWithUTF8String:nameCString]];
}
else {
[ages addObject:[NSString stringWithUTF8String:nameCString]];
}
}
return SQLITE_OK;
}
how can i write "age" entries into NSMutableArray *ages, if i can assign *context just for one NSMutableArray? (in this code, this is NSMutableArray *person)
Surely i should create a separate method for get age entries?
thanks.
In many simple cases like the one in your question it is convinient use most natural representation of tables in objective-c: array of dictionaries. Table is indexed collection of records - so it is an array, and each record is collection of key-value pairs - so it is a dictionary. And you need not change you code when you change column names or even number of colums.
...
NSMutableArray *allRecords= (NSMutableArray *)context;
NSString *columnName;
NSString *columnValue;
NSMutableDictionary * record = [NSMutableDictionary dictionary];
for (int i=0; i < count; i++) {
columnName = [NSString stringWithUTF8String:columns[i]];
if (values[i]){
columnValue = [NSString stringWithUTF8String:values[i]];
}
else{
columnValue = #"";
}
[record setObject:columnValue forKey:columnName];
}
[allRecords addObject:record];
...

How to create a NSString from a format string like #"xxx=%#, yyy=%#" and a NSArray of objects?

Is there any way to create a new
NSString from a format string like #"xxx=%#, yyy=%#" and a NSArray of objects?
In the NSSTring class there are many methods like:
- (id)initWithFormat:(NSString *)format arguments:(va_list)argList
- (id)initWithFormat:(NSString *)format locale:(id)locale arguments:(va_list)argList
+ (id)stringWithFormat:(NSString *)format, ...
but non of them takes a NSArray as an argument, and I cannot find a way to create a va_list from a NSArray...
It is actually not hard to create a va_list from an NSArray. See Matt Gallagher's excellent article on the subject.
Here is an NSString category to do what you want:
#interface NSString (NSArrayFormatExtension)
+ (id)stringWithFormat:(NSString *)format array:(NSArray*) arguments;
#end
#implementation NSString (NSArrayFormatExtension)
+ (id)stringWithFormat:(NSString *)format array:(NSArray*) arguments
{
char *argList = (char *)malloc(sizeof(NSString *) * arguments.count);
[arguments getObjects:(id *)argList];
NSString* result = [[[NSString alloc] initWithFormat:format arguments:argList] autorelease];
free(argList);
return result;
}
#end
Then:
NSString* s = [NSString stringWithFormat:#"xxx=%#, yyy=%#" array:#[#"XXX", #"YYY"]];
NSLog( #"%#", s );
Unfortunately, for 64-bit, the va_list format has changed, so the above code no longer works. And probably should not be used anyway given it depends on the format that is clearly subject to change. Given there is no really robust way to create a va_list, a better solution is to simply limit the number of arguments to a reasonable maximum (say 10) and then call stringWithFormat with the first 10 arguments, something like this:
+ (id)stringWithFormat:(NSString *)format array:(NSArray*) arguments
{
if ( arguments.count > 10 ) {
#throw [NSException exceptionWithName:NSRangeException reason:#"Maximum of 10 arguments allowed" userInfo:#{#"collection": arguments}];
}
NSArray* a = [arguments arrayByAddingObjectsFromArray:#[#"X",#"X",#"X",#"X",#"X",#"X",#"X",#"X",#"X",#"X"]];
return [NSString stringWithFormat:format, a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9] ];
}
Based on this answer using Automatic Reference Counting (ARC): https://stackoverflow.com/a/8217755/881197
Add a category to NSString with the following method:
+ (id)stringWithFormat:(NSString *)format array:(NSArray *)arguments
{
NSRange range = NSMakeRange(0, [arguments count]);
NSMutableData *data = [NSMutableData dataWithLength:sizeof(id) * [arguments count]];
[arguments getObjects:(__unsafe_unretained id *)data.mutableBytes range:range];
NSString *result = [[NSString alloc] initWithFormat:format arguments:data.mutableBytes];
return result;
}
One solution that came to my mind is that I could create a method that works with a fixed large number of arguments like:
+ (NSString *) stringWithFormat: (NSString *) format arguments: (NSArray *) arguments {
return [NSString stringWithFormat: format ,
(arguments.count>0) ? [arguments objectAtIndex: 0]: nil,
(arguments.count>1) ? [arguments objectAtIndex: 1]: nil,
(arguments.count>2) ? [arguments objectAtIndex: 2]: nil,
...
(arguments.count>20) ? [arguments objectAtIndex: 20]: nil];
}
I could also add a check to see if the format string has more than 21 '%' characters and throw an exception in that case.
#Chuck is correct about the fact that you can't convert an NSArray into varargs. However, I don't recommend searching for the pattern %# in the string and replacing it each time. (Replacing characters in the middle of a string is generally quite inefficient, and not a good idea if you can accomplish the same thing in a different way.) Here is a more efficient way to create a string with the format you're describing:
NSArray *array = ...
NSAutoreleasePool *pool = [NSAutoreleasePool new];
NSMutableArray *newArray = [NSMutableArray arrayWithCapacity:[array count]];
for (id object in array) {
[newArray addObject:[NSString stringWithFormat:#"x=%#", [object description]]];
}
NSString *composedString = [[newArray componentsJoinedByString:#", "] retain];
[pool drain];
I included the autorelease pool for good housekeeping, since an autoreleased string will be created for each array entry, and the mutable array is autoreleased as well. You could easily make this into a method/function and return composedString without retaining it, and handle the autorelease elsewhere in the code if desired.
This answer is buggy. As noted, there is no solution to this problem that is guaranteed to work when new platforms are introduced other than using the "10 element array" method.
The answer by solidsun was working well, until I went to compile with 64-bit architecture. This caused an error:
EXC_BAD_ADDRESS type EXC_I386_GPFLT
The solution was to use a slightly different approach for passing the argument list to the method:
+ (id)stringWithFormat:(NSString *)format array:(NSArray*) arguments;
{
__unsafe_unretained id * argList = (__unsafe_unretained id *) calloc(1UL, sizeof(id) * arguments.count);
for (NSInteger i = 0; i < arguments.count; i++) {
argList[i] = arguments[i];
}
NSString* result = [[NSString alloc] initWithFormat:format, *argList] ;// arguments:(void *) argList];
free (argList);
return result;
}
This only works for arrays with a single element
There is no general way to pass an array to a function or method that uses varargs. In this particular case, however, you could fake it by using something like:
for (NSString *currentReplacement in array)
[string stringByReplacingCharactersInRange:[string rangeOfString:#"%#"]
withString:currentReplacement];
EDIT: The accepted answer claims there is a way to do this, but regardless of how fragile this answer might seem, that approach is far more fragile. It relies on implementation-defined behavior (specifically, the structure of a va_list) that is not guaranteed to remain the same. I maintain that my answer is correct and my proposed solution is less fragile since it only relies on defined features of the language and frameworks.
For those who need a Swift solution, here is an extension to do this in Swift
extension String {
static func stringWithFormat(format: String, argumentsArray: Array<AnyObject>) -> String {
let arguments = argumentsArray.map { $0 as! CVarArgType }
let result = String(format:format, arguments:arguments)
return result
}
}
Yes, it is possible. In GCC targeting Mac OS X, at least, va_list is simply a C array, so you'll make one of ids, then tell the NSArray to fill it:
NSArray *argsArray = [[NSProcessInfo processInfo] arguments];
va_list args = malloc(sizeof(id) * [argsArray count]);
NSAssert1(args != nil, #"Couldn't allocate array for %u arguments", [argsArray count]);
[argsArray getObjects:(id *)args];
//Example: NSLogv is the version of NSLog that takes a va_list instead of separate arguments.
NSString *formatSpecifier = #"\n%#";
NSString *format = [#"Arguments:" stringByAppendingString:[formatSpecifier stringByPaddingToLength:[argsArray count] * 3U withString:formatSpecifier startingAtIndex:0U]];
NSLogv(format, args);
free(args);
You shouldn't rely on this nature in code that should be portable. iPhone developers, this is one thing you should definitely test on the device.
- (NSString *)stringWithFormat:(NSString *)format andArguments:(NSArray *)arguments {
NSMutableString *result = [NSMutableString new];
NSArray *components = format ? [format componentsSeparatedByString:#"%#"] : #[#""];
NSUInteger argumentsCount = [arguments count];
NSUInteger componentsCount = [components count] - 1;
NSUInteger iterationCount = argumentsCount < componentsCount ? argumentsCount : componentsCount;
for (NSUInteger i = 0; i < iterationCount; i++) {
[result appendFormat:#"%#%#", components[i], arguments[i]];
}
[result appendString:[components lastObject]];
return iterationCount == 0 ? [result stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] : result;
}
Tested with format and arguments:
NSString *format = #"xxx=%#, yyy=%# last component";
NSArray *arguments = #[#"XXX", #"YYY", #"ZZZ"];
Result: xxx=XXX, yyy=YYY last component
NSString *format = #"xxx=%#, yyy=%# last component";
NSArray *arguments = #[#"XXX", #"YYY"];
Result: xxx=XXX, yyy=YYY last component
NSString *format = #"xxx=%#, yyy=%# last component";
NSArray *arguments = #[#"XXX"];
Result: xxx=XXX last component
NSString *format = #"xxx=%#, yyy=%# last component";
NSArray *arguments = #[];
Result: last component
NSString *format = #"some text";
NSArray *arguments = #[#"XXX", #"YYY", #"ZZZ"];
Result: some text
I found some code on the web that claims that this is possible however I haven't managed to do it myself, however if you don't know the number of arguments in advance you also need to build the format string dynamically so I just don't see the point.
You better off just building the string by iterating the array.
You might find the stringByAppendingString: or stringByAppendingFormat: instance method handy .
One can create a category for NSString and make a function which receives a format, an array and returns the string with replaced objects.
#interface NSString (NSArrayFormat)
+ (NSString *)stringWithFormat:(NSString *)format arrayArguments:(NSArray *)arrayArguments;
#end
#implementation NSString (NSArrayFormat)
+ (NSString *)stringWithFormat:(NSString *)format arrayArguments:(NSArray *)arrayArguments {
static NSString *objectSpecifier = #"%#"; // static is redundant because compiler will optimize this string to have same address
NSMutableString *string = [[NSMutableString alloc] init]; // here we'll create the string
NSRange searchRange = NSMakeRange(0, [format length]);
NSRange rangeOfPlaceholder = NSMakeRange(NSNotFound, 0); // variables are declared here because they're needed for NSAsserts
NSUInteger index;
for (index = 0; index < [arrayArguments count]; ++index) {
rangeOfPlaceholder = [format rangeOfString:objectSpecifier options:0 range:searchRange]; // find next object specifier
if (rangeOfPlaceholder.location != NSNotFound) { // if we found one
NSRange substringRange = NSMakeRange(searchRange.location, rangeOfPlaceholder.location - searchRange.location);
NSString *formatSubstring = [format substringWithRange:substringRange];
[string appendString:formatSubstring]; // copy the format from previous specifier up to this one
NSObject *object = [arrayArguments objectAtIndex:index];
NSString *objectDescription = [object description]; // convert object into string
[string appendString:objectDescription];
searchRange.location = rangeOfPlaceholder.location + [objectSpecifier length]; // update the search range in order to minimize search
searchRange.length = [format length] - searchRange.location;
} else {
break;
}
}
if (rangeOfPlaceholder.location != NSNotFound) { // we need to check if format still specifiers
rangeOfPlaceholder = [format rangeOfString:#"%#" options:0 range:searchRange];
}
NSAssert(rangeOfPlaceholder.location == NSNotFound, #"arrayArguments doesn't have enough objects to fill specified format");
NSAssert(index == [arrayArguments count], #"Objects starting with index %lu from arrayArguments have been ignored because there aren't enough object specifiers!", index);
return string;
}
#end
Because NSArray is created at runtime we cannot provide compile-time warnings, but we can use NSAssert to tell us if number of specifiers is equal with number of objects within array.
Created a project on Github where this category can be found. Also added Chuck's version by using 'stringByReplacingCharactersInRange:' plus some tests.
Using one million objects into array, version with 'stringByReplacingCharactersInRange:' doesn't scale very well (waited about 2 minutes then closed the app). Using the version with NSMutableString, function made the string in about 4 seconds. The tests were made using simulator. Before usage, tests should be done on a real device (use a device with lowest specs).
Edit: On iPhone 5s the version with NSMutableString takes 10.471655s (one million objects); on iPhone 5 takes 21.304876s.
Here's the answer without explicitly creating an array:
NSString *formattedString = [NSString stringWithFormat:#"%# World, Nice %#", #"Hello", #"Day"];
First String is the target string to be formatted, the next string are the string to be inserted in the target.
No, you won't be able to. Variable argument calls are solved at compile time, and your NSArray has contents only at runtime.