I am fairly new to a objective-c or in whole mac/iphone development. My question is how can I acces a data files(text files or flat files) in objective-c? For example I have a sample.txt file, how can I open this files and access its data? Do I need to use a class? And I heard about dictionary, is this term related to my problems?
Please kindly redirect me to a good site.
Thanks alot.
sasayins.
You can use regular fopen and fread to access the contents of a file. Alternatively, you can use NSString if your file contains only text or NSData for non-text data.
NSString *myString = [NSString stringWithContentsOfFile:#"/path/to/file"];
NSData *myData = [NSData dataWithContentsOfFile:#"/path/to/file"];
Edit
#"/path/to/file" a constant “Objective-C” style string. It is different to a regular C string (i.e. without the # prepended) because it behaves like an object; you can send it messages, and it is able to be stored in NSArrays etc. From a Mac Programmer's point of view, these Objective-C strings can be treated just like NSString objects.
The Mac OS X filesystem layout typically looks like this:
/System contains system files similar to C:\windows\
/Library contains libraries, similar to C:\windows\system32\
/Users similar to Windows' C:\Documents and Settings\
/Applications Mac's version of C:\Program Files\
/Developer Where Xcode, SDKs, and other developer tools live.
If your username on your Mac is "smith", then your Home directory is /Users/smith. If you have a file in your Documents folder of your Home directory called data.txt, then you can use the following code to access it (but I wouldn't recommend hard-coding paths like this)
NSString *myString = [NSString stringWithContentsOfFile:#"/Users/smith/Documents/data.txt"];
There are various functions available for reliably obtaining your home directory and other directories of particular interest. The NSString documentation explains the various methods available for manipulating strings containing paths.
Related
In Objective-C (for iOS), is there any way to read the files inside a ZIP archive into memory?
So, each file inside the ZIP is a text file. And what I need to do is to iterate through the files inside the ZIP archive until I locate the one I need by name, and then to read its contents (which is text data) to an NSString variable.
Is this possible to do with zlib? I can't see in the header of this library anything to perform such a task, as reading files inside a zip archive.
Also other libraries i checked on the interent seem to decompress to a directory only, but, what I need is to read the contents of the files inside the zip archive into an NSString variable only.
Thanks
You can do this fairly quickly using my zipzap library:
ZZArchive* archive = [ZZArchive archiveWithContentsOfURL:zipFileURL];
NSString* foundContent = nil;
for (ZZArchiveEntry* entry in archive.entries)
if ([entry.fileName isEqualToString:fileNameToFind])
foundContent = [[NSString alloc] initWithData:entry.data
encoding:NSUTF8StringEncoding];
There are many libraries out there you can use. Google is your friend. libzip, libarchive are just two.
I'm very much a noob/hobbyist programmer, putting together a few simple Mac apps.
I'm confused about resource files.
I have some .png images sitting in a folder in my (XCode 4.4) project.
I also have a .plist (containing a dictionary) sitting in my Supporting Files folder.
To access the .plist, I've added a few lines of code to dig into the Bundle and get the file I'm after (pretty standard, I believe).
To use the .png files, I simply refer to them by name, and when I run from within Xcode everything does what I'm expecting.
But when I export as an Application, the images are still available and work fine, without me going into the Bundle for them.
So my question is - what determines which resource files I should go into the Bundle for, and which resource files I can assume will just be available by virtue of their being in my Supporting Files folder?
Many Thanks for reading this, and for any help you can give me.
I'm guessing that it depends on the class you are using and when you are only referring to them by name its just a convenience thing and XCode does the work nonetheless.
For example for a UIImage you can typeUIImage *image = [UIImage imageNamed:#"something"];
But XCode will do the NSSearchPathForDirectoriesInDomains or the [NSBoundle mainBoundle] thingy at build time.
You can only do the quick name referencing method on a few frequently-used classes and it's just for convenience.
This is my theory anyway, it requires confirmation.
Using ASIHTTPRequest, I downloaded a zip file containing a folder with several audio files. I tried to unzip the file with SSZipArchive and ZipArchive, which are both based on minizip.
When I compile the code, I get this error: Undefined symbols for architecture i386: "_OBJC_CLASS_$_ZipArchive", referenced from: objc-class-ref in AppDelegate.o.
How do I unzip this file in iOS?
I've used ZipArchive with success in the past. It's pretty ligthweight and simple to use, supports password protection, multiple files inside a ZIP, as well as compress & decompress.
The basic usage is:
NSString *filepath = [[NSBundle mainBundle] pathForResource:#"ZipFileName" ofType:#"zip"];
ZipArchive *zipArchive = [[ZipArchive alloc] init];
[zipArchive UnzipOpenFile:filepath Password:#"xxxxxx"];
[zipArchive UnzipFileTo:{pathToDirectory} overWrite:YES];
[zipArchive UnzipCloseFile];
[zipArchive release];
more examples about this package here
I have also tried SSZipArchive in some projects.
Below line would unzip your zip file.
[SSZipArchive unzipFileAtPath:path toDestination:destination];
To start, in iOS 7, Apple introduced the ability to natively zip / unzip files. You also have the option so send the zip files through Mail, Messages, Airdrop and "Open in". The key is: The zip file has to be supported by iOS Some are, and some are not. The first step: Find out if your file is supported. Do this by a simple check of your newly saved file. Try to open it. If it is stuck of "Waiting..." it is probably not supported. Try a different library or use a workaround if this is the case.
Now, doing this programmatically Currently requires the use of a third party library to save zip files and extract them. This is not ideal, since a lot of people / companies avoid using them. That being said, the answer marked correct, ZipArchive is a great third party tool, especially since it now supports Swift. I would recommend using it until Apple introduces a native library.
On iOS6 a ZIP file seems to be handled like a folder. I had success by simply doing the following:
[[NSFileManager defaultManager] copyItemAtPath:[NSURL URLForCachesDirectoryWithAppendedPath:#"ZIP_FILE.zip/Contents/Test.m4a"].path
toPath:[NSURL URLForCachesDirectoryWithAppendedPath:#"Test.m4a"].path
error:nil];
There might be a chance you can even make a directory listing to unzip files with unknown content. Don't know about password protected ZIP files though.
I'm currently working on a project that involves a lot of text file reading. I need to get the contents of the files into NSStrings so I can go and manipulate them further. What I'm using:
NSString *file = [[NSBundle mainBundle] pathForResource:fileName ofType:#"txt"];
NSString *fileContents = [NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:nil];
It works well enough, but as my project grows so does the number of text files. I'm starting to think there should be a more efficient way of searching through the text files included in the project.
In many cases, I know exactly what file I want to search. I have the files organized into group folders based on when they need to be read. Is there any way to narrow the range of the initial file search? It seems like searching through the entire application bundle every time is pointless when I know where the files I need are on a more specific level.
Is there some way to search through groups as opposed to bundles? Can I somehow exclude certain files from the search? From what I can tell, defining custom bundles for this context would not be an appropriate use of the NSBundle functionality.
Have you looked at the method -[NSBundle pathForResource:ofType:inDirectory:]?
I had almost similar kind of situation, for more optimization, i had kept all resource file inside dictionary with some key ,
you may try following
1 -- in our application you may have some kind of pattern or where you could find major group,
2 -- have multiple dictionary each for each group, and inside group, you could store file name,
3 -- As ken suggested to go with the -[NSBundle pathForResource:ofType:inDirectory:]
In my iOS app, I'm downloading content from the web into my /Library/Caches directory. I'd like to represent this directory as an NSBundle for better compatibility with some of the external APIs we're using. (That way, we can simply change [[NSBundle mainBundle] pathForResource...] to [myBundle pathForResource...] whenever it appears.)
The following seems to work fine:
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString* cachesDirectory = [paths objectAtIndex:0];
NSBundle* bundle = [NSBundle bundleWithPath:cachesDirectory];
Better yet, the bundle reflects any changes I make to the /Library/Caches directory. However, I'm concerned because the caches directory is technically not a bundle per Apple's docs. That is to say:
It's not a "directory with a standardized hierarchical structure that holds executable code and the resources used by that code", since there's no code.
It's neither an Application, Framework, nor a Plug-In bundle.
It's most like an Application bundle, but it doesn't contain the required Info.plist or executable.
I could find no mention anywhere of this sort of dynamically-created, resource-only bundle. Is this okay to do?
The /Library/Caches directory will lack some of the standard files which are required in a bundle, like a Contents/ directory or a Contents/Info.plist file, so it may not behave properly when treated as one. Proceed with caution.
Yes, it's absolutely okay to have a resources only bundle. Some of the verbage that you quote pre-exists iOS. In OS X you can dynamically load executable code, that's specifically excluded in iOS.
Localization is an example of resource only bundles.
Edit:
The Bundle Programming Guide says:
Although document formats can leverage the bundle structure to
organize their contents, documents are generally not considered
bundles in the purest sense. A document that is implemented as a
directory and treated as an opaque type is considered to be a document
package, regardless of its internal format. For more information about
document packages, see “Document Packages.”
which says:
There are several ways to access the contents of a document package.
Because a document package is a directory, you can access the
document's contents using any appropriate file-system routines. If you
use a bundle structure for your document package, you can also use the
NSBundle or CFBundleRef routines. Use of a bundle structure is
especially appropriate for documents that store multiple
localizations.
also note that Apple has been telegraphing that it is minimizing the use of "path"/NSString APIs in favor of URL APIs, though existing path APIs will no doubt continue for many more major OS releases.