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?
%s
is used for char*
strings, but %@
should be used with NSStrings. printf
may or may not support %@
, I don't know. If not, you need to use NSString's cStringUsingEncoding or UTF8String to convert to a char*
that you can use.
initWithPrimaryKey:pk:nam:descrip:db
is invalid (or at least very loopy) syntax, BTW, as is initWithPrimaryKey:(NSInteger) pk :(NSString*) nam: (NSString*) descrip: (sqlite3*) db
.
It's important to understand the difference between an NSString
and a char*
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 a char*
string for an NSString
on 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"
.
When printing in the NSLog the NSString should be %@ not %s
精彩评论