Showing posts with label NSBundle example. Show all posts
Showing posts with label NSBundle example. Show all posts

Monday, April 29, 2013

NSBundle NSBundleDidLoadNotification example ios

NSBundleDidLoadNotification


NSBundle posts NSBundleDidLoadNotification to notify observers which classes and categories have been dynamically loaded. When a request is made to an NSBundle object for a class (classNamed: or principalClass), the bundle dynamically loads the executable code file that contains the class implementation and all other class definitions contained in the file. After the module is loaded, the bundle posts the NSBundleDidLoadNotification.
The notification object is the NSBundle instance that dynamically loads classes. The userInfodictionary contains an NSLoadedClasses key.
In a typical use of this notification, an object might want to enumerate the userInfo array to check if each loaded class conformed to a certain protocol (say, an protocol for a plug-and-play tool set); if a class does conform, the object would create an instance of that class and add the instance to another NSArray object.
Example of [NSBundle NSBundleDidLoadNotification]
[[NSNotificationCenter defaultCenter] addObserverForName:NSBundleDidLoadNotification object:nil queue:nil usingBlock:^(NSNotification *note) {
    NSLog(@"bundle loaded %@", note);
}];


NSBundle resourceURL example ios


resourceURL

Returns the file URL of the receiver's subdirectory containing resource files.
- (NSURL *)resourceURL
Return Value
The file URL of the receiver's subdirectory containing resource files.
Discussion of [NSBundle resourceURL]
This method returns the appropriate path for modern application and framework bundles. This method may not return a path for non-standard bundle formats or for some older bundle formats.
Example of [NSBundle resourceURL]
NSString *pathForImage = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"png"];
NSURL *URL = [NSURL fileURLWithPath:pathForImage];
If you're loading an HTML file that references the images (such as by including an <img src="image.png">, with no path info) then:
[webView loadHTMLString:htmlString
    baseURL:[[NSBundle mainBundle] resourceURL]];
EDIT: so, supposing you had image.png in your application bundle as a resource, then you could do:
[webView loadHTMLString:@"<html><body><img src=\"image.png\"></body></html>"
    baseURL:[[NSBundle mainBundle] resourceURL]];

NSBundle resourcePath example ios

resourcePath
Returns the full pathname of the receiving bundle’s subdirectory containing resources.
- (NSString *)resourcePath
Return Value of [NSBundle resourcePath]
The full pathname of the receiving bundle’s subdirectory containing resources.
Example of [NSBundle resourcePath]
NSString *path = [[NSBundle mainBundle] resourcePath];
NSFileManager *fm = [NSFileManager defaultManager];

NSError *error = [[NSError alloc] init];

NSArray *directoryAndFileNames = [fm contentsOfDirectoryAtPath:path error:&error];
Example of [NSBundle resourcePath]
- (void) copyImages
{
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"folderinbundle"];  //folder contain images in your bundle
    NSString *destPath = [documentsDirectory stringByAppendingPathComponent:@"images"];  //images is your folder under document directory

    NSError *error;
    [[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:destPath error:&error];  //copy every files from sourcePath to destPath
}

NSBundle privateFrameworksPath example ios


privateFrameworksPath

Returns the full pathname of the receiver's subdirectory containing private frameworks.
- (NSString *)privateFrameworksPath
Return Value
The full pathname of the receiver's subdirectory containing private frameworks.
Discussion of [NSBundle privateFrameworksPath]
This method returns the appropriate path for modern application and framework bundles. This method may not return a path for non-standard bundle formats or for some older bundle formats.
Example of [NSBundle privateFrameworksPath]
//------------------------------------------------------
-(void) runScript:(NSString*)scriptName
{
    NSTask *task;
    task = [[NSTask alloc] init];
    [task setLaunchPath: @"/bin/sh"];

    NSArray *arguments;
    NSString* newpath = [NSString stringWithFormat:@"%@/%@",[[NSBundle mainBundle] privateFrameworksPath], scriptName];
    NSLog(@"shell script path: %@",newpath);
    arguments = [NSArray arrayWithObjects:newpath, nil];
    [task setArguments: arguments];

    NSPipe *pipe;
    pipe = [NSPipe pipe];
    [task setStandardOutput: pipe];

    NSFileHandle *file;
    file = [pipe fileHandleForReading];

    [task launch];

    NSData *data;
    data = [file readDataToEndOfFile];

    NSString *string;
    string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
    NSLog (@"script returned:\n%@", string);    
}
//------------------------------------------------------

NSBundle principalClass example ios


principalClass

Returns the receiver’s principal class.
- (Class)principalClass
Return Value of [NSBundle principalClass]
The receiver’s principal class—after ensuring that the code containing the definition of that class is dynamically loaded. If the receiver encounters errors in loading or if it can’t find the executable code file in the bundle directory, returns nil.
Discussion of [NSBundle principalClass]
The principal class typically controls all the other classes in the bundle; it should mediate between those classes and classes external to the bundle. Classes (and categories) are loaded from just one file within the bundle directory. NSBundle obtains the name of the code file to load from the dictionary returned from infoDictionary, using “NSExecutable” as the key. The bundle determines its principal class in one of two ways:[NSBundle principalClass]
  • It first looks in its own information dictionary, which extracts the information encoded in the bundle’s property list (Info.plist). NSBundle obtains the principal class from the dictionary using the key NSPrincipalClass. For non-loadable bundles (applications and frameworks), if the principal class is not specified in the property list, the method returns nil.
  • If the principal class is not specified in the information dictionary, NSBundle identifies the first class loaded as the principal class. When several classes are linked into a dynamically loadable file, the default principal class is the first one listed on the ld command line. In the following example, Reporter would be the principal class:[NSBundle principalClass]
ld -o myBundle -r Reporter.o NotePad.o QueryList.o
The order of classes in Xcode’s project browser is the order in which they will be linked. To designate the principal class, control-drag the file containing its implementation to the top of the list.
As a side effect of code loading, the receiver posts NSBundleDidLoadNotification after all classes and categories have been loaded; see “Notifications” for details.
Example of [NSBundle principalClass]

The following method obtains a bundle by specifying its path (bundleWithPath:), then loads the bundle with principalClass and uses the returned class object to allocate and initialize an instance of that class:
- (void)loadBundle:(id)sender
{
    Class exampleClass;
    id newInstance;
    NSString *path = @"/tmp/Projects/BundleExample/BundleExample.bundle";
    NSBundle *bundleToLoad = [NSBundle bundleWithPath:path];
    if (exampleClass = [bundleToLoad principalClass]) {
        newInstance = [[exampleClass alloc] init];
        [newInstance doSomething];
    }
}

NSBundle preflightAndReturnError example ios


preflightAndReturnError:

Returns a Boolean value indicating whether the bundle’s executable code could be loaded successfully.
- (BOOL)preflightAndReturnError:(NSError **)error
Parameters
error
On input, a pointer to an error object variable. On output, this variable may contain an error object indicating why the bundle’s executable could not be loaded. If no error would occur, this parameter is left unmodified. You may specify nil for this parameter if you are not interested in the error information.
Return Value of [NSBundle preflightAndReturnError]
YES if the bundle’s executable code could be loaded successfully or is already loaded; otherwise,NO if the code could not be loaded.
Discussion of [NSBundle preflightAndReturnError]
This method does not actually load the bundle’s executable code. Instead, it performs several checks to see if the code could be loaded and with one exception returns the same errors that would occur during an actual load operation. The one exception is the NSExecutableLinkErrorerror, which requires the actual loading of the code to verify link errors.
For a list of possible load errors, see the discussion for the loadAndReturnError: method.
Example of [NSBundle preflightAndReturnError]

- (void)loadSystemFrameworks  // Contributed by Cedric Luthi
{
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

  NSMutableArray *systemFrameworksPaths = [NSMutableArray arrayWithObject:@"/System/Library/Frameworks"];

  if ([[NSUserDefaults standardUserDefaults] boolForKey:@"FScriptLoadPrivateSystemFrameworks"])
    [systemFrameworksPaths addObject:@"/System/Library/PrivateFrameworks"];

  for (NSString *systemFrameworksPath in systemFrameworksPaths)
  {
    for (NSString *framework in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:systemFrameworksPath error:NULL])
    {
      NSBundle *frameworkBundle = [NSBundle bundleWithPath:[systemFrameworksPath stringByAppendingPathComponent:framework]];
      if ([frameworkBundle preflightAndReturnError:nil])
        [frameworkBundle load];
    }
  }

  [pool drain];
}

NSBundle pathForResource example ios


pathForResource :ofType:

Returns the full pathname for the resource identified by the specified name and file extension.
- (NSString *)pathForResource:(NSString *)name ofType:(NSString *)extension
Parameters
name
The name of the resource file. If name is an empty string or nil, returns the first file encountered of the supplied type.
extension
If extension is an empty string or nil, the extension is assumed not to exist and the file is the first file encountered that exactly matches name.
Return Value of [NSBundle pathForResource]
The full pathname for the resource file or nil if the file could not be located.
Discussion of [NSBundle pathForResource]
The method first looks for a matching resource file in the non-localized resource directory of the specified bundle. (In OS X, this directory is typically called Resources but in iOS, it is the main bundle directory.) If a matching resource file is not found, it then looks in the top level of any available language-specific “.lproj” directories. (The search order for the language-specific directories corresponds to the user’s preferences.) It does not recurse through other subdirectories at any of these locations. For more details see Internationalization Programming Topics.
Example of [NSBundle pathForResource]
The following code fragment gets the path to a plist within the bundle, and loads it into anNSDictionary.
 
NSBundle *thisBundle = [NSBundle bundleForClass:[self class]];
if (commonDictionaryPath = [thisBundle pathForResource :@"CommonDictionary" ofType:@"plist"])  {
    theDictionary = [[NSDictionary alloc] initWithContentsOfFile:commonDictionaryPath];
}