2009-06-10 76 views
2

我是Mac和Objective-C的新手,所以我可能會在這裏咆哮錯誤的樹,很可能有更好的方法來做到這一點。如何將NSString轉換爲我可以與FSCreateDirectoryUnicode一起使用的東西?

我試過下面的代碼,它似乎不正確。看起來我沒有在FSCreateDirectoryUnicode的調用中得到正確的長度。什麼是最簡單的方法來完成這個?

NSString *theString = @"MyFolderName"; 
NSData *unicode = [theString dataUsingEncoding:NSUnicodeStringEncoding allowLossyConversion:NO]; 
FSCreateDirectoryUnicode(&aFolderFSRef, [theString length], [unicode bytes], kFSCatInfoNone, NULL, &newFolderFSRef, NULL, NULL); 

回答

4

您的原始字符串數據有幾個問題。但要做到這一點在可可的最簡單的方法是:

NSString *theString = @"MyFolderName"; 

NSString* path = [NSHomeDirectory() stringByAppendingPathComponent:theString]; 
[[NSFileManager defaultManager] createDirectoryAtPath:path 
              attributes:nil]; 

你做使用FSRef指定路徑的目錄被創建在哪裏。我的例子改爲使用主目錄。如果您真的必須使用FSRef中的目錄並且不知道其路徑,則可能更容易使用FSCreateDirectoryUnicode函數:

編輯:更改了代碼以使用正確的編碼。

NSString *theString = @"MyFolderName"; 
const UniChar* name = (const UniChar*)[theString cStringUsingEncoding:NSUnicodeStringEncoding]; 
FSCreateDirectoryUnicode(&aFolderFSRef, [theString length], name, kFSCatInfoNone, NULL, &newFolderFSRef, NULL, NULL); 

這是在原來的代碼打破的唯一的事情,是dataUsingEncoding返回字符串的外部表示。這意味着數據在開始時包含一個unicode字節順序標記,FSCreateDirectoryUnicode不需要這些標記。

+0

感謝 - 這幫助! (在意識到FSFileManager應該是NSFileManager之後) – staffan 2009-06-10 19:27:58

0

您的代碼看起來不錯。我會使用[unicode length]/2作爲長度,儘管這應該等於所有(或至少幾乎所有)情況下的[theString length]。

或者,你可以使用彌敦道日的NDAlias的NSString + NDCarbonUtilities類別

+ (NSString *)stringWithFSRef:(const FSRef *)aFSRef 
{ 
    NSString  * thePath = nil; 
    CFURLRef theURL = CFURLCreateFromFSRef(kCFAllocatorDefault, aFSRef); 
    if (theURL) 
    { 
     thePath = [(NSURL *)theURL path]; 
     CFRelease (theURL); 
    } 
    return thePath; 
} 

得到的路徑爲您FSRef然後尼古拉的解決方案:

NSString* aFolderPath = [NSString stringWithFSRef:aFolderFSRef]; 
NSString* path = [aFolderPath stringByAppendingPathComponent:theString]; 
[[FSFileManager defaultManager] createDirectoryAtPath:path attributes:nil]; 
相關問題