I am having troubles passing/receiving NSString pointers through function calls. I’m hoping someone can help me see what I’m doing incorrectly.
So this is from my first class…
void addTo(int pk, NSString* nam, NSString *descrip)
{
//open the database
sqlite3 *db;
db = [Item openDB:databasePath];
printf("'%i', '%s', '%s'", pk, nam, descrip);
//create new item with key, name, description, and database
Item *Obj = [[Item alloc]initWithPrimaryKey:pk:nam:descrip:db];
.
.
.
}
And then this is the function in Item.m called as above…
- (id) initWithPrimaryKey:(NSInteger) pk :(NSString*) nam: (NSString*) descrip: (sqlite3*) db{
printf("'%i', '%s', '%s'", pk, nam, descrip);
.
.
.
return self;
}
Let’s say I call addTo with inputs 1234, “Tree”, “plant with leaves”
The print in the first code block outputs what I sent to addTo but the print in initWithPrimaryKey prints the following…
'1234', 'P?a', 'P?a'
Why is this? Or more.. why is it not printing what I expect?
%sis used forchar*strings, but%@should be used with NSStrings.printfmay or may not support%@, I don’t know. If not, you need to use NSString’s cStringUsingEncoding or UTF8String to convert to achar*that you can use.initWithPrimaryKey:pk:nam:descrip:dbis invalid (or at least very loopy) syntax, BTW, as isinitWithPrimaryKey:(NSInteger) pk :(NSString*) nam: (NSString*) descrip: (sqlite3*) db.It’s important to understand the difference between an
NSStringand achar*string. The NSString is a full-fledged object, with about 50 methods that it supports to do all sorts of neat/strange/(and occasionally)obscene things with string values. The two are not in any way interchangeable. And unlike with some C++ libraries, you can’t substitute achar*string for anNSStringon a call and have automatic conversion occur.So using
"letters"for a string will not produce something usable as an NSString — you must use@"letters".