At 8:43 AM -0700 4/6/10, Jon Pugh wrote:
>I had to change to explicitly saving an AliasRecord in an NSData to keep track
>of a file properly.
I should probably clean up and share my code too. This uses an alias relative
to your home folder. The alias is stored in NSUserDefaults under the specified
key. You probably want to retain or copy the path you get from loadPathFromKey
since it's autoreleased or nil.
Enjoy.
Jon
- (void) savePath: (NSString*) path forKey: (NSString*) key
{
FSRef fsFile, fsHome;
AliasHandle aliasHandle;
NSString* homePath = [@"~" stringByExpandingTildeInPath];
OSStatus status = FSPathMakeRef((unsigned char*)[homePath
cStringUsingEncoding: NSUTF8StringEncoding], &fsHome, NULL);
NSAssert(status == 0, @"FSPathMakeRef fsHome failed");
status = FSPathMakeRef((unsigned char*)[path cStringUsingEncoding:
NSUTF8StringEncoding], &fsFile, NULL);
NSAssert(status == 0, @"FSPathMakeRef failed");
OSErr err = FSNewAlias(&fsHome, &fsFile, &aliasHandle);
NSAssert(err == noErr, @"FSNewAlias failed");
NSData* aliasData = [NSData dataWithBytes: *aliasHandle length:
GetAliasSize(aliasHandle)];
[[NSUserDefaults standardUserDefaults] setObject: aliasData forKey:
key];
}
- (NSString*) loadPathFromKey: (NSString*) key
{
NSData* aliasData = [[NSUserDefaults standardUserDefaults] dataForKey:
key];
int aliasLen = [aliasData length];
if (aliasLen > 0)
{
FSRef fsFile, fsHome;
AliasHandle aliasHandle;
OSErr err = PtrToHand([aliasData bytes], (Handle*)&aliasHandle,
aliasLen);
NSAssert(err == noErr, @"PtrToHand failed");
NSString* homePath = [@"~" stringByExpandingTildeInPath];
OSStatus status = FSPathMakeRef((unsigned char*)[homePath
cStringUsingEncoding: NSUTF8StringEncoding], &fsHome, NULL);
NSAssert(status == 0, @"FSPathMakeRef fsHome failed");
Boolean changed;
err = FSResolveAlias(&fsHome, aliasHandle, &fsFile, &changed);
if (err == noErr)
{
char pathC[2*1024];
status = FSRefMakePath(&fsFile, (UInt8*) &pathC,
sizeof(pathC));
NSAssert(status == 0, @"FSRefMakePath failed");
return [NSString stringWithCString: pathC encoding:
NSUTF8StringEncoding];
}
}
else
{
NSLog(@"CardCollectionUserDefault was zero length");
[NSAlert alertWithMessageText: nil
defaultButton: nil
alternateButton: nil
otherButton: nil
informativeTextWithFormat: @"CardCollectionUserDefault
was zero length"];
}
return nil;
}
_______________________________________________
Cocoa-dev mailing list ([email protected])
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com
This email sent to [email protected]