Monday, April 29, 2013

NSBundle bundlePath example ios


bundlePath

Returns the full pathname of the receiver’s bundle directory.
- (NSString *)bundlePath
Return Value
The full pathname of the receiver’s bundle directory.
Example of [NSBundle bundlePath] - 1
    NSEnumerator *iter = [[NSFileManager defaultManager] directoryEnumeratorAtPath:[[NSBundle mainBundle] bundlePath]];
    int count = 0; // number of images
    for (NSString *path in iter) { // iterate through all files in the bundle
         if ([[path pathExtension] isEqualToString:@"png"]) { // test if the extension is "png"
            count++; // increment the number of images
            UIImage *img = [UIImage imageWithContentsOfFile:path];
            // do other things with the image
        }
    }
Example of [NSBundle bundlePath] - 2
+ (NSString *) getAppPath
{
    NSString * appPath = NULL;
    SInt32  minorVersionNum;
    OSErr   err;

    err = Gestalt(gestaltSystemVersionMinor,&minorVersionNum);

    // do this only if we're running on anything *older* than 10.6
    if((noErr == err) && (minorVersionNumber < 6)) 
    {
        // hopefully the below define is enough space for any returned path
        #define kMaxPathLength 512 

        size_t bufferLength = kMaxPathLength;
        char bufferToHoldPath[kMaxPathLength]; 

        // initialize the buffer & guarantee null-terminated strings
        bzero(&bufferToHoldPath,bufferLength);
        if( getcwd(&bufferToHoldPath, bufferLength) != NULL)
        {
            appPath = [NSString stringWithUTF8String: bufferToHoldPath];
        }
    } 

    // this code runs for 10.6 and *newer*, and attempts it on
    // 10.5 only if the above getcwd call failed
    if(NULL == appPath)
    {
        appPath = [[NSBundle mainBundle] bundlePath];
    }

    return(appPath);
}